1;;;; org.el --- Outline-based notes management and organize
2;; Carstens outline-mode for keeping track of everything.
3;; Copyright (C) 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
4;;
5;; Author: Carsten Dominik <dominik at science dot uva dot nl>
6;; Keywords: outlines, hypermedia, calendar, wp
7;; Homepage: http://www.astro.uva.nl/~dominik/Tools/org/
8;; Version: 4.67d
9;;
10;; This file is part of GNU Emacs.
11;;
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 2, or (at your option)
15;; any later version.
16
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.
21
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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27;;
28;;; Commentary:
29;;
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.
32;;
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.
47;;
48;; Installation and Activation
49;; ---------------------------
50;; See the corresponding sections in the manual at
51;;
52;;   http://staff.science.uva.nl/~dominik/Tools/org/org.html#Installation
53;;
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.
61;;
62;; A list of recent changes can be found at
63;; http://www.astro.uva.nl/~dominik/Tools/org/Changes
64;;
65;;; Code:
66
67;;;; Require other packages
68
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(require 'easymenu)
81
82;;;; Customization variables
83
84;;; Version
85
86(defvar org-version "4.67c"
87  "The version number of the file org.el.")
88(defun org-version ()
89  (interactive)
90  (message "Org-mode version %s" org-version))
91
92;;; Compatibility constants
93(defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
94(defconst org-format-transports-properties-p
95  (let ((x "a"))
96    (add-text-properties 0 1 '(test t) x)
97    (get-text-property 0 'test (format "%s" x)))
98  "Does format transport text properties?")
99
100;;; The custom variables
101
102(defgroup org nil
103  "Outline-based notes management and organizer."
104  :tag "Org"
105  :group 'outlines
106  :group 'hypermedia
107  :group 'calendar)
108
109(defgroup org-startup nil
110  "Options concerning startup of Org-mode."
111  :tag "Org Startup"
112  :group 'org)
113
114(defcustom org-startup-folded t
115  "Non-nil means, entering Org-mode will switch to OVERVIEW.
116This can also be configured on a per-file basis by adding one of
117the following lines anywhere in the buffer:
118
119   #+STARTUP: fold
120   #+STARTUP: nofold
121   #+STARTUP: content"
122  :group 'org-startup
123  :type '(choice
124	  (const :tag "nofold: show all" nil)
125	  (const :tag "fold: overview" t)
126	  (const :tag "content: all headlines" content)))
127
128(defcustom org-startup-truncated t
129  "Non-nil means, entering Org-mode will set `truncate-lines'.
130This is useful since some lines containing links can be very long and
131uninteresting.  Also tables look terrible when wrapped."
132  :group 'org-startup
133  :type 'boolean)
134
135(defcustom org-startup-align-all-tables nil
136  "Non-nil means, align all tables when visiting a file.
137This is useful when the column width in tables is forced with <N> cookies
138in table fields.  Such tables will look correct only after the first re-align.
139This can also be configured on a per-file basis by adding one of
140the following lines anywhere in the buffer:
141   #+STARTUP: align
142   #+STARTUP: noalign"
143  :group 'org-startup
144  :type 'boolean)
145
146(defcustom org-insert-mode-line-in-empty-file nil
147  "Non-nil means insert the first line setting Org-mode in empty files.
148When the function `org-mode' is called interactively in an empty file, this
149normally means that the file name does not automatically trigger Org-mode.
150To ensure that the file will always be in Org-mode in the future, a
151line enforcing Org-mode will be inserted into the buffer, if this option
152has been set."
153  :group 'org-startup
154  :type 'boolean)
155
156(defcustom org-CUA-compatible nil
157  "Non-nil means use alternative key bindings for S-<cursor movement>.
158Org-mode used S-<cursor movement> for changing timestamps and priorities.
159S-<cursor movement> is also used for example by `CUA-mode' to select text.
160If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
161alternative bindings.  Setting this variable to t will replace the following
162keys both in Org-mode and in the Org-agenda buffer.
163
164S-RET   -> C-S-RET
165S-up    -> M-p
166S-down  -> M-n
167S-left  -> M--
168S-right -> M-+
169
170If you do not like the alternative keys, take a look at the variable
171`org-disputed-keys'.
172
173This option is only relevant at load-time of Org-mode, and must be set
174*before* org.el is loaded.  Changing it requires a restart of Emacs to
175become effective."
176  :group 'org-startup
177  :type 'boolean)
178
179(defvar org-disputed-keys
180  '((S-up     [(shift up)]      [(meta ?p)])
181    (S-down   [(shift down)]    [(meta ?n)])
182    (S-left   [(shift left)]    [(meta ?-)])
183    (S-right  [(shift right)]   [(meta ?+)])
184    (S-return [(shift return)]  [(control shift return)]))
185  "Keys for which Org-mode and other modes compete.
186This is an alist, cars are symbols for lookup, 1st element is the default key,
187second element will be used when `org-CUA-compatible' is t.")
188
189(defun org-key (key)
190  "Select a key according to `org-CUA-compatible'."
191  (nth (if org-CUA-compatible 2 1)
192       (or (assq key org-disputed-keys)
193	   (error "Invalid Key %s in `org-key'" key))))
194
195(defcustom org-ellipsis nil
196  "The ellipsis to use in the Org-mode outline.
197When nil, just use the standard three dots.  When a string, use that instead,
198and just in Org-mode (which will then use its own display table).
199Changing this requires executing `M-x org-mode' in a buffer to become
200effective."
201  :group 'org-startup
202  :type '(choice (const :tag "Default" nil)
203		 (string :tag "String" :value "...#")))
204
205(defvar org-display-table nil
206  "The display table for org-mode, in case `org-ellipsis' is non-nil.")
207
208(defgroup org-keywords nil
209  "Keywords in Org-mode."
210  :tag "Org Keywords"
211  :group 'org)
212
213(defcustom org-deadline-string "DEADLINE:"
214  "String to mark deadline entries.
215A deadline is this string, followed by a time stamp.  Should be a word,
216terminated by a colon.  You can insert a schedule keyword and
217a timestamp with \\[org-deadline].
218Changes become only effective after restarting Emacs."
219  :group 'org-keywords
220  :type 'string)
221
222(defcustom org-scheduled-string "SCHEDULED:"
223  "String to mark scheduled TODO entries.
224A schedule is this string, followed by a time stamp.  Should be a word,
225terminated by a colon.  You can insert a schedule keyword and
226a timestamp with \\[org-schedule].
227Changes become only effective after restarting Emacs."
228  :group 'org-keywords
229  :type 'string)
230
231(defcustom org-closed-string "CLOSED:"
232  "String used as the prefix for timestamps logging closing a TODO entry."
233  :group 'org-keywords
234  :type 'string)
235
236(defcustom org-clock-string "CLOCK:"
237  "String used as prefix for timestamps clocking work hours on an item."
238  :group 'org-keywords
239  :type 'string)
240
241(defcustom org-comment-string "COMMENT"
242  "Entries starting with this keyword will never be exported.
243An entry can be toggled between COMMENT and normal with
244\\[org-toggle-comment].
245Changes become only effective after restarting Emacs."
246  :group 'org-keywords
247  :type 'string)
248
249(defcustom org-quote-string "QUOTE"
250  "Entries starting with this keyword will be exported in fixed-width font.
251Quoting applies only to the text in the entry following the headline, and does
252not extend beyond the next headline, even if that is lower level.
253An entry can be toggled between QUOTE and normal with
254\\[org-toggle-fixed-width-section]."
255  :group 'org-keywords
256  :type 'string)
257
258(defvar org-repeat-re "\\<REPEAT(\\([-+ 0-9dwmy]+\\))"
259  "Regular expression for specifying repeated events.
260After a match, group 1 contains the repeat expression.")
261
262(defgroup org-structure nil
263  "Options concerning the general structure of Org-mode files."
264  :tag "Org Structure"
265  :group 'org)
266
267(defgroup org-reveal-location nil
268  "Options about how to make context of a location visible."
269  :tag "Org Reveal Location"
270  :group 'org-structure)
271
272(defcustom org-show-hierarchy-above '((default . t))
273  "Non-nil means, show full hierarchy when revealing a location.
274Org-mode often shows locations in an org-mode file which might have
275been invisible before.  When this is set, the hierarchy of headings
276above the exposed location is shown.
277Turning this off for example for sparse trees makes them very compact.
278Instead of t, this can also be an alist specifying this option for different
279contexts.  Valid contexts are
280  agenda         when exposing an entry from the agenda
281  org-goto       when using the command `org-goto' on key C-c C-j
282  occur-tree     when using the command `org-occur' on key C-c /
283  tags-tree      when constructing a sparse tree based on tags matches
284  link-search    when exposing search matches associated with a link
285  mark-goto      when exposing the jump goal of a mark
286  bookmark-jump  when exposing a bookmark location
287  isearch        when exiting from an incremental search
288  default        default for all contexts not set explicitly"
289  :group 'org-reveal-location
290  :type '(choice
291	  (const :tag "Always" t)
292	  (const :tag "Never" nil)
293	  (repeat :greedy t :tag "Individual contexts"
294		  (cons
295		   (choice :tag "Context"
296		    (const agenda)
297		    (const org-goto)
298		    (const occur-tree)
299		    (const tags-tree)
300		    (const link-search)
301		    (const mark-goto)
302		    (const bookmark-jump)
303		    (const isearch)
304		    (const default))
305		   (boolean)))))
306
307(defcustom org-show-following-heading '((default . t))
308  "Non-nil means, show following heading when revealing a location.
309Org-mode often shows locations in an org-mode file which might have
310been invisible before.  When this is set, the heading following the
311match is shown.
312Turning this off for example for sparse trees makes them very compact,
313but makes it harder to edit the location of the match.  In such a case,
314use the command \\[org-reveal] to show more context.
315Instead of t, this can also be an alist specifying this option for different
316contexts.  See `org-show-hierarchy-above' for valid contexts."
317  :group 'org-reveal-location
318  :type '(choice
319	  (const :tag "Always" t)
320	  (const :tag "Never" nil)
321	  (repeat :greedy t :tag "Individual contexts"
322		  (cons
323		   (choice :tag "Context"
324		    (const agenda)
325		    (const org-goto)
326		    (const occur-tree)
327		    (const tags-tree)
328		    (const link-search)
329		    (const mark-goto)
330		    (const bookmark-jump)
331		    (const isearch)
332		    (const default))
333		   (boolean)))))
334
335(defcustom org-show-siblings '((default . nil) (isearch t))
336  "Non-nil means, show all sibling heading when revealing a location.
337Org-mode often shows locations in an org-mode file which might have
338been invisible before.  When this is set, the sibling of the current entry
339heading are all made visible.  If `org-show-hierarchy-above' is t,
340the same happens on each level of the hierarchy above the current entry.
341
342By default this is on for the isearch context, off for all other contexts.
343Turning this off for example for sparse trees makes them very compact,
344but makes it harder to edit the location of the match.  In such a case,
345use the command \\[org-reveal] to show more context.
346Instead of t, this can also be an alist specifying this option for different
347contexts.  See `org-show-hierarchy-above' for valid contexts."
348  :group 'org-reveal-location
349  :type '(choice
350	  (const :tag "Always" t)
351	  (const :tag "Never" nil)
352	  (repeat :greedy t :tag "Individual contexts"
353		  (cons
354		   (choice :tag "Context"
355		    (const agenda)
356		    (const org-goto)
357		    (const occur-tree)
358		    (const tags-tree)
359		    (const link-search)
360		    (const mark-goto)
361		    (const bookmark-jump)
362		    (const isearch)
363		    (const default))
364		   (boolean)))))
365
366(defgroup org-cycle nil
367  "Options concerning visibility cycling in Org-mode."
368  :tag "Org Cycle"
369  :group 'org-structure)
370
371(defcustom org-cycle-global-at-bob t
372  "Cycle globally if cursor is at beginning of buffer and not at a headline.
373This makes it possible to do global cycling without having to use S-TAB or
374C-u TAB.  For this special case to work, the first line of the buffer
375must not be a headline - it may be empty ot some other text.  When used in
376this way, `org-cycle-hook' is disables temporarily, to make sure the
377cursor stays at the beginning of the buffer.
378When this option is nil, don't do anything special at the beginning
379of the buffer."
380  :group 'org-cycle
381  :type 'boolean)
382
383(defcustom org-cycle-emulate-tab t
384  "Where should `org-cycle' emulate TAB.
385nil         Never
386white       Only in completely white lines
387whitestart  Only at the beginning of lines, before the first non-white char.
388t           Everywhere except in headlines
389If TAB is used in a place where it does not emulate TAB, the current subtree
390visibility is cycled."
391  :group 'org-cycle
392  :type '(choice (const :tag "Never" nil)
393		 (const :tag "Only in completely white lines" white)
394		 (const :tag "Before first char in a line" whitestart)
395		 (const :tag "Everywhere except in headlines" t)
396		 ))
397
398(defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
399			    org-optimize-window-after-visibility-change)
400  "Hook that is run after `org-cycle' has changed the buffer visibility.
401The function(s) in this hook must accept a single argument which indicates
402the new state that was set by the most recent `org-cycle' command.  The
403argument is a symbol.  After a global state change, it can have the values
404`overview', `content', or `all'.  After a local state change, it can have
405the values `folded', `children', or `subtree'."
406  :group 'org-cycle
407  :type 'hook)
408
409
410(defgroup org-edit-structure nil
411  "Options concerning structure editing in Org-mode."
412  :tag "Org Edit Structure"
413  :group 'org-structure)
414
415(defcustom org-odd-levels-only nil
416  "Non-nil means, skip even levels and only use odd levels for the outline.
417This has the effect that two stars are being added/taken away in
418promotion/demotion commands.  It also influences how levels are
419handled by the exporters.
420Changing it requires restart of `font-lock-mode' to become effective
421for fontification also in regions already fontified.
422You may also set this on a per-file basis by adding one of the following
423lines to the buffer:
424
425   #+STARTUP: odd
426   #+STARTUP: oddeven"
427  :group 'org-edit-structure
428  :group 'org-font-lock
429  :type 'boolean)
430
431(defcustom org-adapt-indentation t
432  "Non-nil means, adapt indentation when promoting and demoting.
433When this is set and the *entire* text in an entry is indented, the
434indentation is increased by one space in a demotion command, and
435decreased by one in a promotion command.  If any line in the entry
436body starts at column 0, indentation is not changed at all."
437  :group 'org-edit-structure
438  :type 'boolean)
439
440(defcustom org-blank-before-new-entry '((heading . nil)
441					(plain-list-item . nil))
442  "Should `org-insert-heading' leave a blank line before new heading/item?
443The value is an alist, with `heading' and `plain-list-item' as car,
444and a boolean flag as cdr."
445  :group 'org-edit-structure
446  :type '(list
447	  (cons (const heading) (boolean))
448	  (cons (const plain-list-item) (boolean))))
449
450(defcustom org-insert-heading-hook nil
451  "Hook being run after inserting a new heading."
452  :group 'org-edit-structure
453  :type 'boolean)
454
455(defcustom org-enable-fixed-width-editor t
456  "Non-nil means, lines starting with \":\" are treated as fixed-width.
457This currently only means, they are never auto-wrapped.
458When nil, such lines will be treated like ordinary lines.
459See also the QUOTE keyword."
460  :group 'org-edit-structure
461  :type 'boolean)
462
463(defgroup org-sparse-trees nil
464  "Options concerning sparse trees in Org-mode."
465  :tag "Org Sparse Trees"
466  :group 'org-structure)
467
468(defcustom org-highlight-sparse-tree-matches t
469  "Non-nil means, highlight all matches that define a sparse tree.
470The highlights will automatically disappear the next time the buffer is
471changed by an edit command."
472  :group 'org-sparse-trees
473  :type 'boolean)
474
475(defcustom org-remove-highlights-with-change t
476  "Non-nil means, any change to the buffer will remove temporary highlights.
477Such highlights are created by `org-occur' and `org-clock-display'.
478When nil, `C-c C-c needs to be used to get rid of the highlights.
479The highlights created by `org-preview-latex-fragment' always need
480`C-c C-c' to be removed."
481  :group 'org-sparse-trees
482  :group 'org-time
483  :type 'boolean)
484
485
486(defcustom org-occur-hook '(org-first-headline-recenter)
487  "Hook that is run after `org-occur' has constructed a sparse tree.
488This can be used to recenter the window to show as much of the structure
489as possible."
490  :group 'org-sparse-trees
491  :type 'hook)
492
493(defgroup org-plain-lists nil
494  "Options concerning plain lists in Org-mode."
495  :tag "Org Plain lists"
496  :group 'org-structure)
497
498(defcustom org-cycle-include-plain-lists nil
499  "Non-nil means, include plain lists into visibility cycling.
500This means that during cycling, plain list items will *temporarily* be
501interpreted as outline headlines with a level given by 1000+i where i is the
502indentation of the bullet.  In all other operations, plain list items are
503not seen as headlines.  For example, you cannot assign a TODO keyword to
504such an item."
505  :group 'org-plain-lists
506  :type 'boolean)
507
508(defcustom org-plain-list-ordered-item-terminator t
509  "The character that makes a line with leading number an ordered list item.
510Valid values are ?. and ?\).  To get both terminators, use t.  While
511?. may look nicer, it creates the danger that a line with leading
512number may be incorrectly interpreted as an item.  ?\) therefore is
513the safe choice."
514  :group 'org-plain-lists
515  :type '(choice (const :tag "dot like in \"2.\"" ?.)
516		 (const :tag "paren like in \"2)\"" ?\))
517		 (const :tab "both" t)))
518
519(defcustom org-auto-renumber-ordered-lists t
520  "Non-nil means, automatically renumber ordered plain lists.
521Renumbering happens when the sequence have been changed with
522\\[org-shiftmetaup] or \\[org-shiftmetadown].  After other editing commands,
523use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
524  :group 'org-plain-lists
525  :type 'boolean)
526
527(defcustom org-provide-checkbox-statistics t
528  "Non-nil means, update checkbox statistics after insert and toggle.
529When this is set, checkbox statistics is updated each time you either insert
530a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
531with \\[org-ctrl-c-ctrl-c\\]."
532  :group 'org-plain-lists
533  :type 'boolean)
534
535(defgroup org-archive nil
536  "Options concerning archiving in Org-mode."
537  :tag "Org Archive"
538  :group 'org-structure)
539
540(defcustom org-archive-tag "ARCHIVE"
541  "The tag that marks a subtree as archived.
542An archived subtree does not open during visibility cycling, and does
543not contribute to the agenda listings."
544  :group 'org-archive
545  :group 'org-keywords
546  :type 'string)
547
548(defcustom org-agenda-skip-archived-trees t
549  "Non-nil means, the agenda will skip any items located in archived trees.
550An archived tree is a tree marked with the tag ARCHIVE."
551  :group 'org-archive
552  :group 'org-agenda-skip
553  :type 'boolean)
554
555(defcustom org-cycle-open-archived-trees nil
556  "Non-nil means, `org-cycle' will open archived trees.
557An archived tree is a tree marked with the tag ARCHIVE.
558When nil, archived trees will stay folded.  You can still open them with
559normal outline commands like `show-all', but not with the cycling commands."
560  :group 'org-archive
561  :group 'org-cycle
562  :type 'boolean)
563
564(defcustom org-sparse-tree-open-archived-trees nil
565  "Non-nil means sparse tree construction shows matches in archived trees.
566When nil, matches in these trees are highlighted, but the trees are kept in
567collapsed state."
568  :group 'org-archive
569  :group 'org-sparse-trees
570  :type 'boolean)
571
572(defcustom org-archive-location "%s_archive::"
573  "The location where subtrees should be archived.
574This string consists of two parts, separated by a double-colon.
575
576The first part is a file name - when omitted, archiving happens in the same
577file.  %s will be replaced by the current file name (without directory part).
578Archiving to a different file is useful to keep archived entries from
579contributing to the Org-mode Agenda.
580
581The part after the double colon is a headline.  The archived entries will be
582filed under that headline.  When omitted, the subtrees are simply filed away
583at the end of the file, as top-level entries.
584
585Here are a few examples:
586\"%s_archive::\"
587	If the current file is Projects.org, archive in file
588	Projects.org_archive, as top-level trees.  This is the default.
589
590\"::* Archived Tasks\"
591	Archive in the current file, under the top-level headline
592	\"* Archived Tasks\".
593
594\"~/org/archive.org::\"
595	Archive in file ~/org/archive.org (absolute path), as top-level trees.
596
597\"basement::** Finished Tasks\"
598	Archive in file ./basement (relative path), as level 3 trees
599	below the level 2 heading \"** Finished Tasks\".
600
601You may set this option on a per-file basis by adding to the buffer a
602line like
603
604#+ARCHIVE: basement::** Finished Tasks"
605  :group 'org-archive
606  :type 'string)
607
608(defcustom org-archive-mark-done t
609  "Non-nil means, mark entries as DONE when they are moved to the archive file."
610  :group 'org-archive
611  :type 'boolean)
612
613(defcustom org-archive-stamp-time t
614  "Non-nil means, add a time stamp to entries moved to an archive file.
615The time stamp will be added directly after the TODO state keyword in the
616first line, so it is probably best to use this in combinations with
617`org-archive-mark-done'."
618  :group 'org-archive
619  :type 'boolean)
620
621(defgroup org-table nil
622  "Options concerning tables in Org-mode."
623  :tag "Org Table"
624  :group 'org)
625
626(defcustom org-enable-table-editor 'optimized
627  "Non-nil means, lines starting with \"|\" are handled by the table editor.
628When nil, such lines will be treated like ordinary lines.
629
630When equal to the symbol `optimized', the table editor will be optimized to
631do the following:
632- Automatic overwrite mode in front of whitespace in table fields.
633  This makes the structure of the table stay in tact as long as the edited
634  field does not exceed the column width.
635- Minimize the number of realigns.  Normally, the table is aligned each time
636  TAB or RET are pressed to move to another field.  With optimization this
637  happens only if changes to a field might have changed the column width.
638Optimization requires replacing the functions `self-insert-command',
639`delete-char', and `backward-delete-char' in Org-mode buffers, with a
640slight (in fact: unnoticeable) speed impact for normal typing.  Org-mode is
641very good at guessing when a re-align will be necessary, but you can always
642force one with \\[org-ctrl-c-ctrl-c].
643
644If you would like to use the optimized version in Org-mode, but the
645un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
646
647This variable can be used to turn on and off the table editor during a session,
648but in order to toggle optimization, a restart is required.
649
650See also the variable `org-table-auto-blank-field'."
651  :group 'org-table
652  :type '(choice
653	  (const :tag "off" nil)
654	  (const :tag "on" t)
655	  (const :tag "on, optimized" optimized)))
656
657(defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
658  "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
659In the optimized version, the table editor takes over all simple keys that
660normally just insert a character.  In tables, the characters are inserted
661in a way to minimize disturbing the table structure (i.e. in overwrite mode
662for empty fields).  Outside tables, the correct binding of the keys is
663restored.
664
665The default for this option is t if the optimized version is also used in
666Org-mode.  See the variable `org-enable-table-editor' for details.  Changing
667this variable requires a restart of Emacs to become effective."
668  :group 'org-table
669  :type 'boolean)
670
671(defcustom orgtbl-radio-table-templates
672  '((latex-mode "% BEGIN RECEIVE ORGTBL %n
673% END RECEIVE ORGTBL %n
674\\begin{comment}
675#+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
676| | |
677\\end{comment}\n")
678    (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
679@c END RECEIVE ORGTBL %n
680@ignore
681#+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
682| | |
683@end ignore\n")
684    (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
685<!-- END RECEIVE ORGTBL %n -->
686<!--
687#+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
688| | |
689-->\n"))
690  "Templates for radio tables in different major modes.
691All occurrences of %n in a template will be replaced with the name of the
692table, obtained by prompting the user."
693  :group 'org-table
694  :type '(repeat
695	  (list (symbol :tag "Major mode")
696		(string :tag "Format"))))
697
698(defgroup org-table-settings nil
699  "Settings for tables in Org-mode."
700  :tag "Org Table Settings"
701  :group 'org-table)
702
703(defcustom org-table-default-size "5x2"
704  "The default size for newly created tables, Columns x Rows."
705  :group 'org-table-settings
706   :type 'string)
707
708(defcustom org-table-number-regexp
709  "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\)$"
710  "Regular expression for recognizing numbers in table columns.
711If a table column contains mostly numbers, it will be aligned to the
712right.  If not, it will be aligned to the left.
713
714The default value of this option is a regular expression which allows
715anything which looks remotely like a number as used in scientific
716context.  For example, all of the following will be considered a
717number:
718    12    12.2    2.4e-08    2x10^12    4.034+-0.02    2.7(10)  >3.5
719
720Other options offered by the customize interface are more restrictive."
721  :group 'org-table-settings
722  :type '(choice
723	  (const :tag "Positive Integers"
724		 "^[0-9]+$")
725	  (const :tag "Integers"
726		 "^[-+]?[0-9]+$")
727	  (const :tag "Floating Point Numbers"
728		 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
729	  (const :tag "Floating Point Number or Integer"
730		 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
731	  (const :tag "Exponential, Floating point, Integer"
732		 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
733	  (const :tag "Very General Number-Like, including hex"
734		 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\)$")
735	  (string :tag "Regexp:")))
736
737(defcustom org-table-number-fraction 0.5
738  "Fraction of numbers in a column required to make the column align right.
739In a column all non-white fields are considered.  If at least this
740fraction of fields is matched by `org-table-number-fraction',
741alignment to the right border applies."
742  :group 'org-table-settings
743  :type 'number)
744
745(defgroup org-table-editing nil
746  "Bahavior of tables during editing in Org-mode."
747  :tag "Org Table Editing"
748  :group 'org-table)
749
750(defcustom org-table-automatic-realign t
751  "Non-nil means, automatically re-align table when pressing TAB or RETURN.
752When nil, aligning is only done with \\[org-table-align], or after column
753removal/insertion."
754  :group 'org-table-editing
755  :type 'boolean)
756
757(defcustom org-table-auto-blank-field t
758  "Non-nil means, automatically blank table field when starting to type into it.
759This only happens when typing immediately after a field motion
760command (TAB, S-TAB or RET).
761Only relevant when `org-enable-table-editor' is equal to `optimized'."
762  :group 'org-table-editing
763  :type 'boolean)
764
765(defcustom org-table-tab-jumps-over-hlines t
766  "Non-nil means, tab in the last column of a table with jump over a hline.
767If a horizontal separator line is following the current line,
768`org-table-next-field' can either create a new row before that line, or jump
769over the line.  When this option is nil, a new line will be created before
770this line."
771  :group 'org-table-editing
772  :type 'boolean)
773
774(defcustom org-table-tab-recognizes-table.el t
775  "Non-nil means, TAB will automatically notice a table.el table.
776When it sees such a table, it moves point into it and - if necessary -
777calls `table-recognize-table'."
778  :group 'org-table-editing
779  :type 'boolean)
780
781(defgroup org-table-calculation nil
782  "Options concerning tables in Org-mode."
783  :tag "Org Table Calculation"
784  :group 'org-table)
785
786(defcustom org-table-copy-increment t
787  "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
788  :group 'org-table-calculation
789  :type 'boolean)
790
791(defcustom org-calc-default-modes
792  '(calc-internal-prec 12
793    calc-float-format  (float 5)
794    calc-angle-mode    deg
795    calc-prefer-frac   nil
796    calc-symbolic-mode nil
797    calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
798    calc-display-working-message t
799    )
800  "List with Calc mode settings for use in calc-eval for table formulas.
801The list must contain alternating symbols (Calc modes variables and values).
802Don't remove any of the default settings, just change the values.  Org-mode
803relies on the variables to be present in the list."
804  :group 'org-table-calculation
805  :type 'plist)
806
807(defcustom org-table-formula-evaluate-inline t
808  "Non-nil means, TAB and RET evaluate a formula in current table field.
809If the current field starts with an equal sign, it is assumed to be a formula
810which should be evaluated as described in the manual and in the documentation
811string of the command `org-table-eval-formula'.  This feature requires the
812Emacs calc package.
813When this variable is nil, formula calculation is only available through
814the command \\[org-table-eval-formula]."
815  :group 'org-table-calculation
816  :type 'boolean)
817
818;; FIXME this is also a variable that makes Org-mode files non-portable
819;; Maybe I should have a #+ options for constants?
820;; How about the SI/cgs issue?
821(defcustom org-table-formula-use-constants t
822  "Non-nil means, interpret constants in formulas in tables.
823A constant looks like `$c' or `$Grav' and will be replaced before evaluation
824by the value given in `org-table-formula-constants', or by a value obtained
825from the `constants.el' package."
826  :group 'org-table-calculation
827  :type 'boolean)
828
829(defcustom org-table-formula-constants nil
830  "Alist with constant names and values, for use in table formulas.
831The car of each element is a name of a constant, without the `$' before it.
832The cdr is the value as a string.  For example, if you'd like to use the
833speed of light in a formula, you would configure
834
835  (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
836
837and then use it in an equation like `$1*$c'."
838  :group 'org-table-calculation
839  :type '(repeat
840	  (cons (string :tag "name")
841		(string :tag "value"))))
842
843(defcustom org-table-allow-automatic-line-recalculation t
844  "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
845Automatically means, when TAB or RET or C-c C-c are pressed in the line."
846  :group 'org-table-calculation
847  :type 'boolean)
848
849(defgroup org-link nil
850  "Options concerning links in Org-mode."
851  :tag "Org Link"
852  :group 'org)
853
854(defvar org-link-abbrev-alist-local nil
855  "buffer-local version of `org-link-abbrev-alist', which see.
856The value of this is taken from the #+LINK lines.")
857(make-variable-buffer-local 'org-link-abbrev-alist-local)
858
859(defcustom org-link-abbrev-alist nil
860  "Alist of link abbreviations.
861The car of each element is a string, to be replaced at the start of a link.
862The cdrs are replacement values, like (\"linkkey\" . REPLACE).  Abbreviated
863links in Org-mode buffers can have an optional tag after a double colon, e.g.
864
865     [[linkkey:tag][description]]
866
867If REPLACE is a string, the tag will simply be appended to create the link.
868If the string contains \"%s\", the tag will be inserted there.  REPLACE may
869also be a function that will be called with the tag as the only argument to
870create the link.  See the manual for examples."
871  :group 'org-link
872  :type 'alist)
873
874(defcustom org-descriptive-links t
875  "Non-nil means, hide link part and only show description of bracket links.
876Bracket links are like [[link][descritpion]]. This variable sets the initial
877state in new org-mode buffers.  The setting can then be toggled on a
878per-buffer basis from the Org->Hyperlinks menu."
879  :group 'org-link
880  :type 'boolean)
881
882(defcustom org-link-file-path-type 'adaptive
883  "How the path name in file links should be stored.
884Valid values are:
885
886relative  relative to the current directory, i.e. the directory of the file
887          into which the link is being inserted.
888absolute  absolute path, if possible with ~ for home directory.
889noabbrev  absolute path, no abbreviation of home directory.
890adaptive  Use relative path for files in the current directory and sub-
891          directories of it.  For other files, use an absolute path."
892  :group 'org-link
893  :type '(choice
894	  (const relative)
895	  (const absolute)
896	  (const noabbrev)
897	  (const adaptive)))
898
899(defcustom org-activate-links '(bracket angle plain radio tag date)
900  "Types of links that should be activated in Org-mode files.
901This is a list of symbols, each leading to the activation of a certain link
902type.  In principle, it does not hurt to turn on most link types - there may
903be a small gain when turning off unused link types.  The types are:
904
905bracket   The recommended [[link][description]] or [[link]] links with hiding.
906angular   Links in angular brackes that may contain whitespace like
907          <bbdb:Carsten Dominik>.
908plain     Plain links in normal text, no whitespace, like http://google.com.
909radio     Text that is matched by a radio target, see manual for details.
910tag       Tag settings in a headline (link to tag search).
911date      Time stamps (link to calendar).
912
913Changing this variable requires a restart of Emacs to become effective."
914  :group 'org-link
915  :type '(set (const :tag "Double bracket links (new style)" bracket)
916	      (const :tag "Angular bracket links (old style)" angular)
917	      (const :tag "plain text links" plain)
918	      (const :tag "Radio target matches" radio)
919	      (const :tag "Tags" tag)
920	      (const :tag "Timestamps" date)))
921
922(defgroup org-link-store nil
923  "Options concerning storing links in Org-mode"
924  :tag "Org Store Link"
925  :group 'org-link)
926
927(defcustom org-email-link-description-format "Email %c: %.30s"
928  "Format of the description part of a link to an email or usenet message.
929The following %-excapes will be replaced by corresponding information:
930
931%F   full \"From\" field
932%f   name, taken from \"From\" field, address if no name
933%T   full \"To\" field
934%t   first name in \"To\" field, address if no name
935%c   correspondent.  Unually \"from NAME\", but if you sent it yourself, it
936     will be \"to NAME\".  See also the variable `org-from-is-user-regexp'.
937%s   subject
938%m   message-id.
939
940You may use normal field width specification between the % and the letter.
941This is for example useful to limit the length of the subject.
942
943Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
944  :group 'org-link-store
945  :type 'string)
946
947(defcustom org-from-is-user-regexp
948  (let (r1 r2)
949    (when (and user-mail-address (not (string= user-mail-address "")))
950      (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
951    (when (and user-full-name (not (string= user-full-name "")))
952      (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
953    (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
954  "Regexp mached against the \"From:\" header of an email or usenet message.
955It should match if the message is from the user him/herself."
956  :group 'org-link-store
957  :type 'regexp)
958
959(defcustom org-context-in-file-links t
960  "Non-nil means, file links from `org-store-link' contain context.
961A search string will be added to the file name with :: as separator and
962used to find the context when the link is activated by the command
963`org-open-at-point'.
964Using a prefix arg to the command \\[org-store-link] (`org-store-link')
965negates this setting for the duration of the command."
966  :group 'org-link-store
967  :type 'boolean)
968
969(defcustom org-keep-stored-link-after-insertion nil
970  "Non-nil means, keep link in list for entire session.
971
972The command `org-store-link' adds a link pointing to the current
973location to an internal list.  These links accumulate during a session.
974The command `org-insert-link' can be used to insert links into any
975Org-mode file (offering completion for all stored links).  When this
976option is nil, every link which has been inserted once using \\[org-insert-link]
977will be removed from the list, to make completing the unused links
978more efficient."
979  :group 'org-link-store
980  :type 'boolean)
981
982(defcustom org-usenet-links-prefer-google nil
983  "Non-nil means, `org-store-link' will create web links to Google groups.
984When nil, Gnus will be used for such links.
985Using a prefix arg to the command \\[org-store-link] (`org-store-link')
986negates this setting for the duration of the command."
987  :group 'org-link-store
988  :type 'boolean)
989
990(defgroup org-link-follow nil
991  "Options concerning following links in Org-mode"
992  :tag "Org Follow Link"
993  :group 'org-link)
994
995(defcustom org-tab-follows-link nil
996  "Non-nil means, on links TAB will follow the link.
997Needs to be set before org.el is loaded."
998  :group 'org-link-follow
999  :type 'boolean)
1000
1001(defcustom org-return-follows-link nil
1002  "Non-nil means, on links RET will follow the link.
1003Needs to be set before org.el is loaded."
1004  :group 'org-link-follow
1005  :type 'boolean)
1006
1007(defcustom org-mouse-1-follows-link t
1008  "Non-nil means, mouse-1 on a link will follow the link.
1009A longer mouse click will still set point.  Does not wortk on XEmacs.
1010Needs to be set before org.el is loaded."
1011  :group 'org-link-follow
1012  :type 'boolean)
1013
1014(defcustom org-mark-ring-length 4
1015  "Number of different positions to be recorded in the ring
1016Changing this requires a restart of Emacs to work correctly."
1017  :group 'org-link-follow
1018  :type 'interger)
1019
1020(defcustom org-link-frame-setup
1021  '((vm . vm-visit-folder-other-frame)
1022    (gnus . gnus-other-frame)
1023    (file . find-file-other-window))
1024  "Setup the frame configuration for following links.
1025When following a link with Emacs, it may often be useful to display
1026this link in another window or frame.  This variable can be used to
1027set this up for the different types of links.
1028For VM, use any of
1029    `vm-visit-folder'
1030    `vm-visit-folder-other-frame'
1031For Gnus, use any of
1032    `gnus'
1033    `gnus-other-frame'
1034For FILE, use any of
1035    `find-file'
1036    `find-file-other-window'
1037    `find-file-other-frame'
1038For the calendar, use the variable `calendar-setup'.
1039For BBDB, it is currently only possible to display the matches in
1040another window."
1041  :group 'org-link-follow
1042  :type '(list
1043	  (cons (const vm)
1044		(choice
1045		 (const vm-visit-folder)
1046		 (const vm-visit-folder-other-window)
1047		 (const vm-visit-folder-other-frame)))
1048	  (cons (const gnus)
1049		(choice
1050		 (const gnus)
1051		 (const gnus-other-frame)))
1052	  (cons (const file)
1053		(choice
1054		 (const find-file)
1055		 (const find-file-other-window)
1056		 (const find-file-other-frame)))))
1057
1058(defcustom org-display-internal-link-with-indirect-buffer nil
1059  "Non-nil means, use indirect buffer to display infile links.
1060Activating internal links (from one location in a file to another location
1061in the same file) normally just jumps to the location.  When the link is
1062activated with a C-u prefix (or with mouse-3), the link is displayed in
1063another window.  When this option is set, the other window actually displays
1064an indirect buffer clone of the current buffer, to avoid any visibility
1065changes to the current buffer."
1066  :group 'org-link-follow
1067  :type 'boolean)
1068
1069(defcustom org-open-non-existing-files nil
1070  "Non-nil means, `org-open-file' will open non-existing files.
1071When nil, an error will be generated."
1072  :group 'org-link-follow
1073  :type 'boolean)
1074
1075(defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1076  "Function and arguments to call for following mailto links.
1077This is a list with the first element being a lisp function, and the
1078remaining elements being arguments to the function.  In string arguments,
1079%a will be replaced by the address, and %s will be replaced by the subject
1080if one was given like in <mailto:arthur@galaxy.org::this subject>."
1081  :group 'org-link-follow
1082  :type '(choice
1083	  (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1084	  (const :tag "compose-mail" (compose-mail "%a" "%s"))
1085	  (const :tag "message-mail" (message-mail "%a" "%s"))
1086	  (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1087
1088(defcustom org-confirm-shell-link-function 'yes-or-no-p
1089  "Non-nil means, ask for confirmation before executing shell links.
1090Shell links can be dangerous, just thing about a link
1091
1092     [[shell:rm -rf ~/*][Google Search]]
1093
1094This link would show up in your Org-mode document as \"Google Search\"
1095but really it would remove your entire home directory.
1096Therefore I *definitely* advise against setting this variable to nil.
1097Just change it to `y-or-n-p' of you want to confirm with a single key press
1098rather than having to type \"yes\"."
1099  :group 'org-link-follow
1100  :type '(choice
1101	  (const :tag "with yes-or-no (safer)" yes-or-no-p)
1102	  (const :tag "with y-or-n (faster)" y-or-n-p)
1103	  (const :tag "no confirmation (dangerous)" nil)))
1104
1105(defcustom org-confirm-elisp-link-function 'yes-or-no-p
1106  "Non-nil means, ask for confirmation before executing elisp links.
1107Elisp links can be dangerous, just think about a link
1108
1109     [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1110
1111This link would show up in your Org-mode document as \"Google Search\"
1112but really it would remove your entire home directory.
1113Therefore I *definitely* advise against setting this variable to nil.
1114Just change it to `y-or-n-p' of you want to confirm with a single key press
1115rather than having to type \"yes\"."
1116  :group 'org-link-follow
1117  :type '(choice
1118	  (const :tag "with yes-or-no (safer)" yes-or-no-p)
1119	  (const :tag "with y-or-n (faster)" y-or-n-p)
1120	  (const :tag "no confirmation (dangerous)" nil)))
1121
1122(defconst org-file-apps-defaults-gnu
1123  '((remote . emacs)
1124    (t . mailcap))
1125  "Default file applications on a UNIX or GNU/Linux system.
1126See `org-file-apps'.")
1127
1128(defconst org-file-apps-defaults-macosx
1129  '((remote . emacs)
1130    (t . "open %s")
1131    ("ps"     . "gv %s")
1132    ("ps.gz"  . "gv %s")
1133    ("eps"    . "gv %s")
1134    ("eps.gz" . "gv %s")
1135    ("dvi"    . "xdvi %s")
1136    ("fig"    . "xfig %s"))
1137  "Default file applications on a MacOS X system.
1138The system \"open\" is known as a default, but we use X11 applications
1139for some files for which the OS does not have a good default.
1140See `org-file-apps'.")
1141
1142(defconst org-file-apps-defaults-windowsnt
1143  (list
1144   '(remote . emacs)
1145   (cons t
1146	 (list (if (featurep 'xemacs)
1147		   'mswindows-shell-execute
1148		 'w32-shell-execute)
1149	       "open" 'file)))
1150  "Default file applications on a Windows NT system.
1151The system \"open\" is used for most files.
1152See `org-file-apps'.")
1153
1154(defcustom org-file-apps
1155  '(
1156    ("txt" . emacs)
1157    ("tex" . emacs)
1158    ("ltx" . emacs)
1159    ("org" . emacs)
1160    ("el"  . emacs)
1161    ("bib" . emacs)
1162    )
1163  "External applications for opening `file:path' items in a document.
1164Org-mode uses system defaults for different file types, but
1165you can use this variable to set the application for a given file
1166extension.  The entries in this list are cons cells where the car identifies
1167files and the cdr the corresponding command.  Possible values for the
1168file identifier are
1169 \"ext\"         A string identifying an extension
1170 `directory'   Matches a directory
1171 `remote'      Matches a remote file, accessible through tramp or efs.
1172               Remote files most likely should be visited through Emacs
1173               because external applications cannot handle such paths.
1174 t             Default for all remaining files
1175
1176Possible values for the command are:
1177 `emacs'       The file will be visited by the current Emacs process.
1178 `default'     Use the default application for this file type.
1179 string        A command to be executed by a shell; %s will be replaced
1180	       by the path to the file.
1181 sexp          A Lisp form which will be evaluated.  The file path will
1182	       be available in the Lisp variable `file'.
1183For more examples, see the system specific constants
1184`org-file-apps-defaults-macosx'
1185`org-file-apps-defaults-windowsnt'
1186`org-file-apps-defaults-gnu'."
1187  :group 'org-link-follow
1188  :type '(repeat
1189	  (cons (choice :value ""
1190			(string :tag "Extension")
1191			(const :tag "Default for unrecognized files" t)
1192			(const :tag "Remote file" remote)
1193			(const :tag "Links to a directory" directory))
1194		(choice :value ""
1195			(const :tag "Visit with Emacs" emacs)
1196			(const :tag "Use system default" default)
1197			(string :tag "Command")
1198			(sexp :tag "Lisp form")))))
1199
1200(defcustom org-mhe-search-all-folders nil
1201  "Non-nil means, that the search for the mh-message will be extended to
1202all folders if the message cannot be found in the folder given in the link.
1203Searching all folders is very efficient with one of the search engines
1204supported by MH-E, but will be slow with pick."
1205  :group 'org-link-follow
1206  :type 'boolean)
1207
1208(defgroup org-remember nil
1209  "Options concerning interaction with remember.el."
1210  :tag "Org Remember"
1211  :group 'org)
1212
1213(defcustom org-directory "~/org"
1214  "Directory with org files.
1215This directory will be used as default to prompt for org files.
1216Used by the hooks for remember.el."
1217  :group 'org-remember
1218  :type 'directory)
1219
1220(defcustom org-default-notes-file "~/.notes"
1221  "Default target for storing notes.
1222Used by the hooks for remember.el.  This can be a string, or nil to mean
1223the value of `remember-data-file'.
1224You can set this on a per-template basis with the variable
1225`org-remember-templates'."
1226  :group 'org-remember
1227  :type '(choice
1228	  (const :tag "Default from remember-data-file" nil)
1229	  file))
1230
1231(defcustom org-remember-default-headline ""
1232  "The headline that should be the default location in the notes file.
1233When filing remember notes, the cursor will start at that position.
1234You can set this on a per-template basis with the variable
1235`org-remember-templates'."
1236  :group 'org-remember
1237  :type 'string)
1238
1239(defcustom org-remember-templates nil
1240  "Templates for the creation of remember buffers.
1241When nil, just let remember make the buffer.
1242When not nil, this is a list of 4-element lists.  In each entry, the first
1243element is a character, a unique key to select this template.
1244The second element is the template.  The third element is optional and can
1245specify a destination file for remember items created with this template.
1246The default file is given by `org-default-notes-file'.  An optional third
1247element can specify the headline in that file that should be offered
1248first when the user is asked to file the entry.  The default headline is
1249given in the variable `org-remember-default-headline'.
1250
1251The template specifies the structure of the remember buffer.  It should have
1252a first line starting with a star, to act as the org-mode headline.
1253Furthermore, the following %-escapes will be replaced with content:
1254
1255  %^{prompt}  prompt the user for a string and replace this sequence with it.
1256  %t          time stamp, date only
1257  %T          time stamp with date and time
1258  %u, %U      like the above, but inactive time stamps
1259  %^t         like %t, but prompt for date.  Similarly %^T, %^u, %^U
1260              You may define a prompt like %^{Please specify birthday}t
1261  %n          user name (taken from `user-full-name')
1262  %a          annotation, normally the link created with org-store-link
1263  %i          initial content, the region when remember is called with C-u.
1264              If %i is indented, the entire inserted text will be indented
1265              as well.
1266
1267  %?          After completing the template, position cursor here.
1268
1269Apart from these general escapes, you can access information specific to the
1270link type that is created.  For example, calling `remember' in emails or gnus
1271will record the author and the subject of the message, which you can access
1272with %:author and %:subject, respectively.  Here is a complete list of what
1273is recorded for each link type.
1274
1275Link type          |  Available information
1276-------------------+------------------------------------------------------
1277bbdb               |  %:type %:name %:company
1278vm, wl, mh, rmail  |  %:type %:subject %:message-id
1279                   |  %:from %:fromname %:fromaddress
1280                   |  %:to   %:toname   %:toaddress
1281                   |  %:fromto (either \"to NAME\" or \"from NAME\")
1282gnus               |  %:group, for messages also all email fields
1283w3, w3m            |  %:type %:url
1284info               |  %:type %:file %:node
1285calendar           |  %:type %:date"
1286  :group 'org-remember
1287  :get (lambda (var) ; Make sure all entries have 4 elements
1288	 (mapcar (lambda (x)
1289		   (cond ((= (length x) 3) (append x '("")))
1290			 ((= (length x) 2) (append x '("" "")))
1291			 (t x)))
1292		 (default-value var)))
1293  :type '(repeat
1294	  :tag "enabled"
1295	  (list :value (?a "\n" nil nil)
1296		(character :tag "Selection Key")
1297		(string :tag "Template")
1298		(file :tag "Destination file (optional)")
1299		(string :tag "Destination headline (optional)"))))
1300
1301(defcustom org-reverse-note-order nil
1302  "Non-nil means, store new notes at the beginning of a file or entry.
1303When nil, new notes will be filed to the end of a file or entry."
1304  :group 'org-remember
1305  :type '(choice
1306	  (const :tag "Reverse always" t)
1307	  (const :tag "Reverse never" nil)
1308	  (repeat :tag "By file name regexp"
1309		  (cons regexp boolean))))
1310
1311(defgroup org-todo nil
1312  "Options concerning TODO items in Org-mode."
1313  :tag "Org TODO"
1314  :group 'org)
1315
1316(defgroup org-progress nil
1317  "Options concerning Progress logging in Org-mode."
1318  :tag "Org Progress"
1319  :group 'org-time)
1320
1321(defcustom org-todo-keywords '("TODO" "DONE")
1322  "List of TODO entry keywords.
1323\\<org-mode-map>By default, this is '(\"TODO\" \"DONE\").  The last entry in the list is
1324considered to mean that the entry is \"done\".  All the other mean that
1325action is required, and will make the entry show up in todo lists, diaries
1326etc.
1327The command \\[org-todo] cycles an entry through these states, and an
1328additional state where no keyword is present.  For details about this
1329cycling, see also the variable `org-todo-interpretation'
1330Changes become only effective after restarting Emacs."
1331  :group 'org-todo
1332  :group 'org-keywords
1333  :type '(repeat (string :tag "Keyword")))
1334
1335(defcustom org-todo-interpretation 'sequence
1336  "Controls how TODO keywords are interpreted.
1337This variable is only relevant if `org-todo-keywords' contains more than two
1338states.  \\<org-mode-map>Possible values are `sequence' and `type'.
1339
1340When `sequence', \\[org-todo] will always switch to the next state in the
1341`org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1342to state when executed several times in direct succession.  Otherwise, it
1343switches directly to DONE from any state.
1344See the manual for more information."
1345  :group 'org-todo
1346  :group 'org-keywords
1347  :type '(choice (const sequence)
1348		 (const type)))
1349
1350(defcustom org-after-todo-state-change-hook nil
1351  "Hook which is run after the state of a TODO item was changed.
1352The new state (a string with a TODO keyword, or nil) is available in the
1353Lisp variable `state'."
1354  :group 'org-todo
1355  :type 'hook)
1356
1357(defcustom org-log-done nil
1358  "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1359When the state of an entry is changed from nothing to TODO, remove a previous
1360closing date.
1361
1362This can also be a list of symbols indicating under which conditions
1363the time stamp recording the action should be annotated with a short note.
1364Valid members of this list are
1365
1366  done       Offer to record a note when marking entries done
1367  state      Offer to record a note whenever changing the TODO state
1368             of an item.  This is only relevant if TODO keywords are
1369             interpreted as sequence, see variable `org-todo-interpretation'.
1370             When `state' is set, this includes tracking `done'.
1371  clock-out  Offer to record a note when clocking out of an item.
1372
1373A separate window will then pop up and allow you to type a note.
1374After finishing with C-c C-c, the note will be added directly after the
1375timestamp, as a plain list item.  See also the variable
1376`org-log-note-headings'.
1377
1378Logging can also be configured on a per-file basis by adding one of
1379the following lines anywhere in the buffer:
1380
1381   #+STARTUP: logdone
1382   #+STARTUP: nologging
1383   #+STARTUP: lognotedone
1384   #+STARTUP: lognotestate
1385   #+STARTUP: lognoteclock-out"
1386  :group 'org-todo
1387  :group 'org-progress
1388  :type '(choice
1389	  (const :tag "off" nil)
1390	  (const :tag "on" t)
1391	  (set :tag "on, with notes, detailed control" :greedy t :value (done)
1392	       (const :tag "when item is marked DONE" done)
1393	       (const :tag "when TODO state changes" state)
1394	       (const :tag "when clocking out" clock-out))))
1395
1396(defcustom org-log-note-headings
1397  '((done . "CLOSING NOTE %t")
1398    (state . "State %-12s %t")
1399    (clock-out . ""))
1400  "Headings for notes added when clocking out or closing TODO items.
1401The value is an alist, with the car being a sympol indicating the note
1402context, and the cdr is the heading to be used.  The heading may also be the
1403empty string.
1404%t in the heading will be replaced by a time stamp.
1405%s will be replaced by the new TODO state, in double quotes.
1406%u will be replaced by the user name.
1407%U will be replaced by the full user name."
1408  :group  'org-todo
1409  :group  'org-progress
1410  :type '(list :greedy t
1411	  (cons (const :tag "Heading when closing an item" done) string)
1412	  (cons (const :tag
1413		       "Heading when changing todo state (todo sequence only)"
1414		       state) string)
1415	  (cons (const :tag "Heading when clocking out" clock-out) string)))
1416
1417(defcustom org-allow-auto-repeat t
1418  "Non-nil means, find REPEAT cookies in entries and apply them.
1419A repeat cookie looks like REPEAT(+1m) and causes deadlines and schedules
1420to repeat themselves shifted by a certain amount of time, each time an
1421entry is marked DONE."
1422  :group 'org-todo
1423  :group 'org-progress
1424  :type 'boolean)
1425
1426(defgroup org-priorities nil
1427  "Priorities in Org-mode."
1428  :tag "Org Priorities"
1429  :group 'org-todo)
1430
1431(defcustom org-default-priority ?B
1432  "The default priority of TODO items.
1433This is the priority an item get if no explicit priority is given."
1434  :group 'org-priorities
1435  :type 'character)
1436
1437(defcustom org-lowest-priority ?C
1438  "The lowest priority of TODO items.  A character like ?A, ?B etc."
1439  :group 'org-priorities
1440  :type 'character)
1441
1442(defgroup org-time nil
1443  "Options concerning time stamps and deadlines in Org-mode."
1444  :tag "Org Time"
1445  :group 'org)
1446
1447(defcustom org-insert-labeled-timestamps-at-point nil
1448  "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1449When nil, these labeled time stamps are forces into the second line of an
1450entry, just after the headline.  When scheduling from the global TODO list,
1451the time stamp will always be forced into the second line."
1452  :group 'org-time
1453  :type 'boolean)
1454
1455(defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1456  "Formats for `format-time-string' which are used for time stamps.
1457It is not recommended to change this constant.")
1458
1459(defcustom org-time-stamp-rounding-minutes 0
1460  "Number of minutes to round time stamps to upon insertion.
1461When zero, insert the time unmodified.  Useful rounding numbers
1462should be factors of 60, so for example 5, 10, 15.
1463When this is not zero, you can still force an exact time-stamp by using
1464a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1465  :group 'org-time
1466  :type 'integer)
1467
1468(defcustom org-display-custom-times nil
1469  "Non-nil means, overlay custom formats over all time stamps.
1470The formats are defined through the variable `org-time-stamp-custom-formats'.
1471To turn this on on a per-file basis, insert anywhere in the file:
1472   #+STARTUP: customtime"
1473  :group 'org-time
1474  :set 'set-default
1475  :type 'sexp)
1476(make-variable-buffer-local 'org-display-custom-times)
1477
1478(defcustom org-time-stamp-custom-formats
1479  '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1480  "Custom formats for time stamps.  See `format-time-string' for the syntax.
1481These are overlayed over the default ISO format if the variable
1482`org-display-custom-times' is set."
1483  :group 'org-time
1484  :type 'sexp)
1485
1486(defun org-time-stamp-format (&optional long inactive)
1487  "Get the right format for a time string."
1488  (let ((f (if long (cdr org-time-stamp-formats)
1489	     (car org-time-stamp-formats))))
1490    (if inactive
1491	(concat "[" (substring f 1 -1) "]")
1492      f)))
1493
1494(defcustom org-deadline-warning-days 30
1495  "No. of days before expiration during which a deadline becomes active.
1496This variable governs the display in sparse trees and in the agenda."
1497  :group 'org-time
1498  :type 'number)
1499
1500(defcustom org-popup-calendar-for-date-prompt t
1501  "Non-nil means, pop up a calendar when prompting for a date.
1502In the calendar, the date can be selected with mouse-1.  However, the
1503minibuffer will also be active, and you can simply enter the date as well.
1504When nil, only the minibuffer will be available."
1505  :group 'org-time
1506  :type 'boolean)
1507
1508(defcustom org-calendar-follow-timestamp-change t
1509  "Non-nil means, make the calendar window follow timestamp changes.
1510When a timestamp is modified and the calendar window is visible, it will be
1511moved to the new date."
1512  :group 'org-time
1513  :type 'boolean)
1514
1515(defgroup org-tags nil
1516  "Options concerning tags in Org-mode."
1517  :tag "Org Tags"
1518  :group 'org)
1519
1520(defcustom org-tag-alist nil
1521  "List of tags allowed in Org-mode files.
1522When this list is nil, Org-mode will base TAG input on what is already in the
1523buffer.
1524The value of this variable is an alist, the car may be (and should) be a
1525character that is used to select that tag through the fast-tag-selection
1526interface.  See the manual for details."
1527  :group 'org-tags
1528  :type '(repeat
1529	  (choice
1530	   (cons   (string    :tag "Tag name")
1531		   (character :tag "Access char"))
1532	   (const :tag "Start radio group" (:startgroup))
1533	   (const :tag "End radio group" (:endgroup)))))
1534
1535(defcustom org-use-fast-tag-selection 'auto
1536  "Non-nil means, use fast tag selection scheme.
1537This is a special interface to select and deselect tags with single keys.
1538When nil, fast selection is never used.
1539When the symbol `auto', fast selection is used if and only if selection
1540characters for tags have been configured, either through the variable
1541`org-tag-alist' or through a #+TAGS line in the buffer.
1542When t, fast selection is always used and selection keys are assigned
1543automatically if necessary."
1544  :group 'org-tags
1545  :type '(choice
1546	  (const :tag "Always" t)
1547	  (const :tag "Never" nil)
1548	  (const :tag "When selection characters are configured" 'auto)))
1549
1550(defcustom org-fast-tag-selection-single-key nil
1551  "Non-nil means, fast tag selection exits after first change.
1552When nil, you have to press RET to exit it.
1553During fast tag selection, you can toggle this flag with `C-c'.
1554This variable can also have the value `expert'.  In this case, the window
1555displaying the tags menu is not even shown, until you press C-c again."
1556  :group 'org-tags
1557  :type '(choice
1558	  (const :tag "No" nil)
1559	  (const :tag "Yes" t)
1560	  (const :tag "Expert" expert)))
1561
1562(defcustom org-tags-column 48
1563  "The column to which tags should be indented in a headline.
1564If this number is positive, it specifies the column.  If it is negative,
1565it means that the tags should be flushright to that column.  For example,
1566-79 works well for a normal 80 character screen."
1567  :group 'org-tags
1568  :type 'integer)
1569
1570(defcustom org-auto-align-tags t
1571  "Non-nil means, realign tags after pro/demotion of TODO state change.
1572These operations change the length of a headline and therefore shift
1573the tags around.  With this options turned on, after each such operation
1574the tags are again aligned to `org-tags-column'."
1575  :group 'org-tags
1576  :type 'boolean)
1577
1578(defcustom org-use-tag-inheritance t
1579  "Non-nil means, tags in levels apply also for sublevels.
1580When nil, only the tags directly given in a specific line apply there.
1581If you turn off this option, you very likely want to turn on the
1582companion option `org-tags-match-list-sublevels'."
1583  :group 'org-tags
1584  :type 'boolean)
1585
1586(defcustom org-tags-match-list-sublevels nil
1587  "Non-nil means list also sublevels of headlines matching tag search.
1588Because of tag inheritance (see variable `org-use-tag-inheritance'),
1589the sublevels of a headline matching a tag search often also match
1590the same search.  Listing all of them can create very long lists.
1591Setting this variable to nil causes subtrees of a match to be skipped.
1592This option is off by default, because inheritance in on.  If you turn
1593inheritance off, you very likely want to turn this option on.
1594
1595As a special case, if the tag search is restricted to TODO items, the
1596value of this variable is ignored and sublevels are always checked, to
1597make sure all corresponding TODO items find their way into the list."
1598  :group 'org-tags
1599  :type 'boolean)
1600
1601(defvar org-tags-history nil
1602  "History of minibuffer reads for tags.")
1603(defvar org-last-tags-completion-table nil
1604  "The last used completion table for tags.")
1605
1606(defgroup org-agenda nil
1607  "Options concerning agenda views in Org-mode."
1608  :tag "Org Agenda"
1609  :group 'org)
1610
1611(defvar org-category nil
1612  "Variable used by org files to set a category for agenda display.
1613Such files should use a file variable to set it, for example
1614
1615   -*- mode: org; org-category: \"ELisp\"
1616
1617or contain a special line
1618
1619#+CATEGORY: ELisp
1620
1621If the file does not specify a category, then file's base name
1622is used instead.")
1623(make-variable-buffer-local 'org-category)
1624
1625(defcustom org-agenda-files nil
1626  "The files to be used for agenda display.
1627Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1628\\[org-remove-file].  You can also use customize to edit the list.
1629
1630If the value of the variable is not a list but a single file name, then
1631the list of agenda files is actually stored and maintained in that file, one
1632agenda file per line."
1633  :group 'org-agenda
1634  :type '(choice
1635	  (repeat :tag "List of files" file)
1636	  (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1637
1638
1639(defcustom org-agenda-confirm-kill 1
1640  "When set, remote killing from the agenda buffer needs confirmation.
1641When t, a confirmation is always needed.  When a number N, confirmation is
1642only needed when the text to be killed contains more than N non-white lines."
1643  :group 'org-agenda
1644  :type '(choice
1645	  (const :tag "Never" nil)
1646	  (const :tag "Always" t)
1647	  (number :tag "When more than N lines")))
1648
1649(defcustom org-calendar-to-agenda-key [?c]
1650  "The key to be installed in `calendar-mode-map' for switching to the agenda.
1651The command `org-calendar-goto-agenda' will be bound to this key.  The
1652default is the character `c' because then `c' can be used to switch back and
1653forth between agenda and calendar."
1654  :group 'org-agenda
1655  :type 'sexp)
1656
1657(defgroup org-agenda-custom-commands nil
1658 "Options concerning agenda views in Org-mode."
1659 :tag "Org Agenda Custom Commands"
1660 :group 'org-agenda)
1661
1662(defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1663  "Custom commands for the agenda.
1664These commands will be offered on the splash screen displayed by the
1665agenda dispatcher \\[org-agenda].  Each entry is a list like this:
1666
1667   (key type match options)
1668
1669key     The key (a single char as a string) to be associated with the command.
1670type    The command type, any of the following symbols:
1671         todo        Entries with a specific TODO keyword, in all agenda files.
1672         tags        Tags match in all agenda files.
1673         tags-todo   Tags match in all agenda files, TODO entries only.
1674         todo-tree   Sparse tree of specific TODO keyword in *current* file.
1675         tags-tree   Sparse tree with all tags matches in *current* file.
1676         occur-tree  Occur sparse tree for *current* file.
1677match   What to search for:
1678         - a single keyword for TODO keyword searches
1679         - a tags match expression for tags searches
1680         - a regular expression for occur searches
1681options  A list of option setttings, similar to that in a let form, so like
1682         this: ((opt1 val1) (opt2 val2) ...)
1683
1684You can also define a set of commands, to create a composite agenda buffer.
1685In this case, an entry looks like this:
1686
1687  (key desc (cmd1 cmd2 ...) general-options)
1688
1689where
1690
1691desc   A description string to be displayed in the dispatcher menu.
1692cmd    An agenda command, similar to the above.  However, tree commands
1693       are no allowed, but instead you can get agenda and global todo list.
1694       So valid commands for a set are:
1695       (agenda)
1696       (alltodo)
1697       (stuck)
1698       (todo \"match\" options)
1699       (tags \"match\" options )
1700       (tags-todo \"match\" options)
1701
1702Each command can carry a list of options, and another set of options can be
1703given for the whole set of commands.  Individual command options take
1704precedence over the general options."
1705  :group 'org-agenda-custom-commands
1706  :type '(repeat
1707	  (choice
1708	   (list :tag "Single command"
1709		 (string :tag "Key")
1710		 (choice
1711		  (const :tag "Tags search (all agenda files)" tags)
1712		  (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
1713		  (const :tag "TODO keyword search (all agenda files)" todo)
1714		  (const :tag "Tags sparse tree (current buffer)" tags-tree)
1715		  (const :tag "TODO keyword tree (current buffer)" todo-tree)
1716		  (const :tag "Occur tree (current buffer)" occur-tree)
1717		  (symbol :tag "Other, user-defined function"))
1718		 (string :tag "Match")
1719		 (repeat :tag "Local options"
1720			 (list (variable :tag "Option") (sexp :tag "Value"))))
1721	   (list :tag "Command series, all agenda files"
1722		 (string :tag "Key")
1723		 (string :tag "Description")
1724		 (repeat
1725		  (choice
1726		   (const :tag "Agenda" (agenda))
1727		   (const :tag "TODO list" (alltodo))
1728		   (const :tag "Stuck projects" (stuck))
1729		   (list :tag "Tags search"
1730			 (const :format "" tags)
1731			 (string :tag "Match")
1732			 (repeat :tag "Local options"
1733				 (list (variable :tag "Option")
1734				       (sexp :tag "Value"))))
1735
1736		   (list :tag "Tags search, TODO entries only"
1737			 (const :format "" tags-todo)
1738			 (string :tag "Match")
1739			 (repeat :tag "Local options"
1740				 (list (variable :tag "Option")
1741				       (sexp :tag "Value"))))
1742
1743		   (list :tag "TODO keyword search"
1744			 (const :format "" todo)
1745			 (string :tag "Match")
1746			 (repeat :tag "Local options"
1747				 (list (variable :tag "Option")
1748				       (sexp :tag "Value"))))
1749
1750		   (list :tag "Other, user-defined function"
1751			 (symbol :tag "function")
1752			 (string :tag "Match")
1753			 (repeat :tag "Local options"
1754				 (list (variable :tag "Option")
1755				       (sexp :tag "Value"))))))
1756
1757		 (repeat :tag "General options"
1758			 (list (variable :tag "Option")
1759			       (sexp :tag "Value")))))))
1760
1761(defcustom org-stuck-projects
1762  '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil)
1763  "How to identify stuck projects.
1764This is a list of three items:
17651. A tags/todo matcher string that is used to identify a project.
1766   The entire tree below a headline matched by this is considered a project.
17672. A list of TODO keywords itentifying non-stuck projects.
1768   If the project subtree contains any headline with one of these todo
1769   keywords, the project is consitered to be not stuck.
17703. A list of tags identifying non-stuck projects.
1771   If the project subtree contains any headline with one of these tags,
1772   the project is consitered to be not stuck.
1773
1774After defining this variable, you may use \\[org-agenda-list-stuck-projects]
1775or `C-c a #' to produce the list."
1776  :group 'org-agenda-custom-commands
1777  :type '(list
1778	  (string :tag "Tags/TODO match to identify a project")
1779	  (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
1780	  (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))))
1781
1782
1783(defgroup org-agenda-skip nil
1784 "Options concerning skipping parts of agenda files."
1785 :tag "Org Agenda Skip"
1786 :group 'org-agenda)
1787
1788(defcustom org-agenda-todo-list-sublevels t
1789  "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1790When nil, the sublevels of a TODO entry are not checked, resulting in
1791potentially much shorter TODO lists."
1792  :group 'org-agenda-skip
1793  :group 'org-todo
1794  :type 'boolean)
1795
1796(defcustom org-agenda-todo-ignore-scheduled nil
1797  "Non-nil means, don't show scheduled entries in the global todo list.
1798The idea behind this is that by scheduling it, you have already taken care
1799of this item."
1800  :group 'org-agenda-skip
1801  :group 'org-todo
1802  :type 'boolean)
1803
1804(defcustom org-agenda-todo-ignore-deadlines nil
1805  "Non-nil means, don't show near deadline entries in the global todo list.
1806Near means closer than `org-deadline-warning-days' days.
1807The idea behind this is that such items will appear in the agenda anyway."
1808  :group 'org-agenda-skip
1809  :group 'org-todo
1810  :type 'boolean)
1811
1812(defcustom org-agenda-skip-scheduled-if-done nil
1813  "Non-nil means don't show scheduled items in agenda when they are done.
1814This is relevant for the daily/weekly agenda, not for the TODO list."
1815  :group 'org-agenda-skip
1816  :type 'boolean)
1817
1818(defcustom org-timeline-show-empty-dates 3
1819  "Non-nil means, `org-timeline' also shows dates without an entry.
1820When nil, only the days which actually have entries are shown.
1821When t, all days between the first and the last date are shown.
1822When an integer, show also empty dates, but if there is a gap of more than
1823N days, just insert a special line indicating the size of the gap."
1824  :group 'org-agenda-skip
1825  :type '(choice
1826	  (const :tag "None" nil)
1827	  (const :tag "All" t)
1828	  (number :tag "at most")))
1829
1830
1831(defgroup org-agenda-startup nil
1832  "Options concerning initial settings in the Agenda in Org Mode."
1833  :tag "Org Agenda Startup"
1834  :group 'org-agenda)
1835
1836(defcustom org-finalize-agenda-hook nil
1837  "Hook run just before displaying an agenda buffer."
1838  :group 'org-agenda-startup
1839  :type 'hook)
1840
1841(defcustom org-agenda-mouse-1-follows-link nil
1842  "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1843A longer mouse click will still set point.  Does not wortk on XEmacs.
1844Needs to be set before org.el is loaded."
1845  :group 'org-agenda-startup
1846  :type 'boolean)
1847
1848(defcustom org-agenda-start-with-follow-mode nil
1849  "The initial value of follwo-mode in a newly created agenda window."
1850  :group 'org-agenda-startup
1851  :type 'boolean)
1852
1853(defgroup org-agenda-windows nil
1854  "Options concerning the windows used by the Agenda in Org Mode."
1855  :tag "Org Agenda Windows"
1856  :group 'org-agenda)
1857
1858(defcustom org-agenda-window-setup 'reorganize-frame
1859  "How the agenda buffer should be displayed.
1860Possible values for this option are:
1861
1862current-window    Show agenda in the current window, keeping all other windows.
1863other-frame       Use `switch-to-buffer-other-frame' to display agenda.
1864other-window      Use `switch-to-buffer-other-window' to display agenda.
1865reorganize-frame  Show only two windows on the current frame, the current
1866                  window and the agenda.
1867See also the variable `org-agenda-restore-windows-after-quit'."
1868  :group 'org-agenda-windows
1869  :type '(choice
1870	  (const current-window)
1871	  (const other-frame)
1872	  (const other-window)
1873	  (const reorganize-frame)))
1874
1875(defcustom org-agenda-restore-windows-after-quit nil
1876  "Non-nil means, restore window configuration open exiting agenda.
1877Before the window configuration is changed for displaying the agenda,
1878the current status is recorded.  When the agenda is exited with
1879`q' or `x' and this option is set, the old state is restored.  If
1880`org-agenda-window-setup' is `other-frame', the value of this
1881option will be ignored.."
1882  :group 'org-agenda-windows
1883  :type 'boolean)
1884
1885(defcustom org-indirect-buffer-display 'other-window
1886  "How should indirect tree buffers be displayed?
1887This applies to indirect buffers created with the commands
1888\\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1889Valid values are:
1890current-window   Display in the current window
1891other-window     Just display in another window.
1892dedicated-frame  Create one new frame, and re-use it each time.
1893new-frame        Make a new frame each time."
1894  :group 'org-structure
1895  :group 'org-agenda-windows
1896  :type '(choice
1897	  (const :tag "In current window" current-window)
1898	  (const :tag "In current frame, other window" other-window)
1899	  (const :tag "Each time a new frame" new-frame)
1900	  (const :tag "One dedicated frame" dedicated-frame)))
1901
1902(defgroup org-agenda-daily/weekly nil
1903  "Options concerning the daily/weekly agenda."
1904  :tag "Org Agenda Daily/Weekly"
1905  :group 'org-agenda)
1906
1907(defcustom org-agenda-ndays 7
1908  "Number of days to include in overview display.
1909Should be 1 or 7."
1910  :group 'org-agenda-daily/weekly
1911  :type 'number)
1912
1913(defcustom org-agenda-start-on-weekday 1
1914  "Non-nil means, start the overview always on the specified weekday.
19150 denotes Sunday, 1 denotes Monday etc.
1916When nil, always start on the current day."
1917  :group 'org-agenda-daily/weekly
1918  :type '(choice (const :tag "Today" nil)
1919		 (number :tag "Weekday No.")))
1920
1921(defcustom org-agenda-show-all-dates t
1922  "Non-nil means, `org-agenda' shows every day in the selected range.
1923When nil, only the days which actually have entries are shown."
1924  :group 'org-agenda-daily/weekly
1925  :type 'boolean)
1926
1927(defcustom org-agenda-date-format "%A %d %B %Y"
1928  "Format string for displaying dates in the agenda.
1929Used by the daily/weekly agenda and by the timeline.  This should be
1930a format string understood by `format-time-string'.
1931FIXME: Not used currently, because of timezone problem."
1932  :group 'org-agenda-daily/weekly
1933  :type 'string)
1934
1935(defcustom org-agenda-include-diary nil
1936  "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1937  :group 'org-agenda-daily/weekly
1938  :type 'boolean)
1939
1940(defcustom org-agenda-include-all-todo nil
1941  "Set  means weekly/daily agenda will always contain all TODO entries.
1942The TODO entries will be listed at the top of the agenda, before
1943the entries for specific days."
1944  :group 'org-agenda-daily/weekly
1945  :type 'boolean)
1946
1947(defgroup org-agenda-time-grid nil
1948  "Options concerning the time grid in the Org-mode Agenda."
1949  :tag "Org Agenda Time Grid"
1950  :group 'org-agenda)
1951
1952(defcustom org-agenda-use-time-grid t
1953  "Non-nil means, show a time grid in the agenda schedule.
1954A time grid is a set of lines for specific times (like every two hours between
19558:00 and 20:00).  The items scheduled for a day at specific times are
1956sorted in between these lines.
1957For details about when the grid will be shown, and what it will look like, see
1958the variable `org-agenda-time-grid'."
1959  :group 'org-agenda-time-grid
1960  :type 'boolean)
1961
1962(defcustom org-agenda-time-grid
1963  '((daily today require-timed)
1964    "----------------"
1965    (800 1000 1200 1400 1600 1800 2000))
1966
1967  "The settings for time grid for agenda display.
1968This is a list of three items.  The first item is again a list.  It contains
1969symbols specifying conditions when the grid should be displayed:
1970
1971 daily         if the agenda shows a single day
1972 weekly        if the agenda shows an entire week
1973 today         show grid on current date, independent of daily/weekly display
1974 require-timed show grid only if at least one item has a time specification
1975
1976The second item is a string which will be places behing the grid time.
1977
1978The third item is a list of integers, indicating the times that should have
1979a grid line."
1980  :group 'org-agenda-time-grid
1981  :type
1982  '(list
1983    (set :greedy t :tag "Grid Display Options"
1984	 (const :tag "Show grid in single day agenda display" daily)
1985	 (const :tag "Show grid in weekly agenda display" weekly)
1986	 (const :tag "Always show grid for today" today)
1987	 (const :tag "Show grid only if any timed entries are present"
1988		require-timed)
1989	 (const :tag "Skip grid times already present in an entry"
1990		remove-match))
1991    (string :tag "Grid String")
1992    (repeat :tag "Grid Times" (integer :tag "Time"))))
1993
1994(defgroup org-agenda-sorting nil
1995  "Options concerning sorting in the Org-mode Agenda."
1996  :tag "Org Agenda Sorting"
1997  :group 'org-agenda)
1998
1999(let ((sorting-choice
2000       '(choice
2001	 (const time-up) (const time-down)
2002	 (const category-keep) (const category-up) (const category-down)
2003	 (const tag-down) (const tag-up)
2004	 (const priority-up) (const priority-down))))
2005
2006  (defcustom org-agenda-sorting-strategy
2007    '((agenda time-up category-keep priority-down)
2008      (todo category-keep priority-down)
2009      (tags category-keep))
2010    "Sorting structure for the agenda items of a single day.
2011This is a list of symbols which will be used in sequence to determine
2012if an entry should be listed before another entry.  The following
2013symbols are recognized:
2014
2015time-up         Put entries with time-of-day indications first, early first
2016time-down       Put entries with time-of-day indications first, late first
2017category-keep   Keep the default order of categories, corresponding to the
2018		sequence in `org-agenda-files'.
2019category-up     Sort alphabetically by category, A-Z.
2020category-down   Sort alphabetically by category, Z-A.
2021tag-up          Sort alphabetically by last tag, A-Z.
2022tag-down        Sort alphabetically by last tag, Z-A.
2023priority-up     Sort numerically by priority, high priority last.
2024priority-down   Sort numerically by priority, high priority first.
2025
2026The different possibilities will be tried in sequence, and testing stops
2027if one comparison returns a \"not-equal\".  For example, the default
2028    '(time-up category-keep priority-down)
2029means: Pull out all entries having a specified time of day and sort them,
2030in order to make a time schedule for the current day the first thing in the
2031agenda listing for the day.  Of the entries without a time indication, keep
2032the grouped in categories, don't sort the categories, but keep them in
2033the sequence given in `org-agenda-files'.  Within each category sort by
2034priority.
2035
2036Leaving out `category-keep' would mean that items will be sorted across
2037categories by priority."
2038  :group 'org-agenda-sorting
2039  :type `(choice
2040	  (repeat :tag "General" ,sorting-choice)
2041	  (list :tag "Individually"
2042		(cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2043		      (repeat ,sorting-choice))
2044		(cons (const :tag "Strategy for TODO lists" todo)
2045		      (repeat ,sorting-choice))
2046		(cons (const :tag "Strategy for Tags matches" tags)
2047		      (repeat ,sorting-choice))))))
2048
2049(defcustom org-sort-agenda-notime-is-late t
2050  "Non-nil means, items without time are considered late.
2051This is only relevant for sorting.  When t, items which have no explicit
2052time like 15:30 will be considered as 99:01, i.e. later than any items which
2053do have a time.  When nil, the default time is before 0:00.  You can use this
2054option to decide if the schedule for today should come before or after timeless
2055agenda entries."
2056  :group 'org-agenda-sorting
2057  :type 'boolean)
2058
2059(defgroup org-agenda-prefix nil
2060  "Options concerning the entry prefix in the Org-mode agenda display."
2061  :tag "Org Agenda Prefix"
2062  :group 'org-agenda)
2063
2064(defcustom org-agenda-prefix-format
2065  '((agenda  . "  %-12:c%?-12t% s")
2066    (timeline  . "  % s")
2067    (todo  . "  %-12:c")
2068    (tags  . "  %-12:c"))
2069  "Format specifications for the prefix of items in the agenda views.
2070An alist with four entries, for the different agenda types.  The keys to the
2071sublists are `agenda', `timeline', `todo', and `tags'.  The values
2072are format strings.
2073This format works similar to a printf format, with the following meaning:
2074
2075  %c   the category of the item, \"Diary\" for entries from the diary, or
2076       as given by the CATEGORY keyword or derived from the file name.
2077  %T   the *last* tag of the item.  Last because inherited tags come
2078       first in the list.
2079  %t   the time-of-day specification if one applies to the entry, in the
2080       format HH:MM
2081  %s   Scheduling/Deadline information, a short string
2082
2083All specifiers work basically like the standard `%s' of printf, but may
2084contain two additional characters:  A question mark just after the `%' and
2085a whitespace/punctuation character just before the final letter.
2086
2087If the first character after `%' is a question mark, the entire field
2088will only be included if the corresponding value applies to the
2089current entry.  This is useful for fields which should have fixed
2090width when present, but zero width when absent.  For example,
2091\"%?-12t\" will result in a 12 character time field if a time of the
2092day is specified, but will completely disappear in entries which do
2093not contain a time.
2094
2095If there is punctuation or whitespace character just before the final
2096format letter, this character will be appended to the field value if
2097the value is not empty.  For example, the format \"%-12:c\" leads to
2098\"Diary: \" if the category is \"Diary\".  If the category were be
2099empty, no additional colon would be interted.
2100
2101The default value of this option is \"  %-12:c%?-12t% s\", meaning:
2102- Indent the line with two space characters
2103- Give the category in a 12 chars wide field, padded with whitespace on
2104  the right (because of `-').  Append a colon if there is a category
2105  (because of `:').
2106- If there is a time-of-day, put it into a 12 chars wide field.  If no
2107  time, don't put in an empty field, just skip it (because of '?').
2108- Finally, put the scheduling information and append a whitespace.
2109
2110As another example, if you don't want the time-of-day of entries in
2111the prefix, you could use:
2112
2113  (setq org-agenda-prefix-format \"  %-11:c% s\")
2114
2115See also the variables `org-agenda-remove-times-when-in-prefix' and
2116`org-agenda-remove-tags-when-in-prefix'."
2117  :type '(choice
2118	  (string :tag "General format")
2119	  (list :greedy t :tag "View dependent"
2120		(cons  (const agenda) (string :tag "Format"))
2121		(cons  (const timeline) (string :tag "Format"))
2122		(cons  (const todo) (string :tag "Format"))
2123		(cons  (const tags) (string :tag "Format"))))
2124  :group 'org-agenda-prefix)
2125
2126(defvar org-prefix-format-compiled nil
2127  "The compiled version of the most recently used prefix format.
2128See the variable `org-agenda-prefix-format'.")
2129
2130(defcustom org-agenda-remove-times-when-in-prefix t
2131  "Non-nil means, remove duplicate time specifications in agenda items.
2132When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2133time-of-day specification in a headline or diary entry is extracted and
2134placed into the prefix.  If this option is non-nil, the original specification
2135\(a timestamp or -range, or just a plain time(range) specification like
213611:30-4pm) will be removed for agenda display.  This makes the agenda less
2137cluttered.
2138The option can be t or nil.  It may also be the symbol `beg', indicating
2139that the time should only be removed what it is located at the beginning of
2140the headline/diary entry."
2141  :group 'org-agenda-prefix
2142  :type '(choice
2143	  (const :tag "Always" t)
2144	  (const :tag "Never" nil)
2145	  (const :tag "When at beginning of entry" beg)))
2146
2147(defcustom org-agenda-remove-tags-when-in-prefix nil
2148  "Non-nil means, remove the tags from the headline copy in the agenda.
2149When this is the symbol `prefix', only remove tags when
2150`org-agenda-prefix-format' contains a `%T' specifier."
2151  :group 'org-agenda-prefix
2152  :type '(choice
2153	  (const :tag "Always" t)
2154	  (const :tag "Never" nil)
2155	  (const :tag "When prefix format contains %T" prefix)))
2156
2157(defcustom org-agenda-align-tags-to-column 65
2158  "Shift tags in agenda items to this column."
2159  :group 'org-agenda-prefix
2160  :type 'integer)
2161
2162(defgroup org-latex nil
2163  "Options for embedding LaTeX code into Org-mode"
2164  :tag "Org LaTeX"
2165  :group 'org)
2166
2167(defcustom org-format-latex-options
2168  '(:foreground "Black" :background "Transparent" :scale 1.0
2169		:matchers ("begin" "$" "$$" "\\(" "\\["))
2170  "Options for creating images from LaTeX fragments.
2171This is a property list with the following properties:
2172:foreground  the foreground color, for example \"Black\".
2173:background  the background color, or \"Transparent\".
2174:scale       a scaling factor for the size of the images
2175:matchers    a list indicating which matchers should be used to
2176             find LaTeX fragments.  Valid members of this list are:
2177             \"begin\"  find environments
2178             \"$\"      find math expressions surrounded by $...$
2179             \"$$\"     find math expressions surrounded by $$....$$
2180             \"\\(\"     find math expressions surrounded by \\(...\\)
2181             \"\\ [\"    find math expressions surrounded by \\ [...\\]"
2182  :group 'org-latex
2183  :type 'plist)
2184
2185(defgroup org-export nil
2186  "Options for exporting org-listings."
2187  :tag "Org Export"
2188  :group 'org)
2189
2190(defgroup org-export-general nil
2191  "General options for exporting Org-mode files."
2192  :tag "Org Export General"
2193  :group 'org-export)
2194
2195(defcustom org-export-publishing-directory "."
2196  "Path to the location where exported files should be located.
2197This path may be relative to the directory where the Org-mode file lives.
2198The default is to put them into the same directory as the Org-mode file.
2199The variable may also be an alist with export types `:html', `:ascii',
2200`:ical', or `:xoxo' and the corresponding directories.  If a direcoty path
2201is relative, it is interpreted relative to the directory where the exported
2202Org-mode files lives."
2203  :group 'org-export-general
2204  :type '(choice
2205	  (directory)
2206	  (repeat
2207	   (cons
2208	    (choice :tag "Type"
2209		    (const :html) (const :ascii) (const :ical) (const :xoxo))
2210	    (directory)))))
2211
2212(defcustom org-export-language-setup
2213  '(("en"  "Author"          "Date"  "Table of Contents")
2214    ("cs"  "Autor"           "Datum" "Obsah")
2215    ("da"  "Ophavsmand"      "Dato"  "Indhold")
2216    ("de"  "Autor"           "Datum" "Inhaltsverzeichnis")
2217    ("es"  "Autor"           "Fecha" "\xccndice")
2218    ("fr"  "Auteur"          "Date"  "Table des Mati\xe8res")
2219    ("it"  "Autore"          "Data"  "Indice")
2220    ("nl"  "Auteur"          "Datum" "Inhoudsopgave")
2221    ("nn"  "Forfattar"       "Dato"  "Innhold")  ;; nn = Norsk (nynorsk)
2222    ("sv"  "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2223  "Terms used in export text, translated to different languages.
2224Use the variable `org-export-default-language' to set the language,
2225or use the +OPTION lines for a per-file setting."
2226  :group 'org-export-general
2227  :type '(repeat
2228	  (list
2229	   (string :tag "HTML language tag")
2230	   (string :tag "Author")
2231	   (string :tag "Date")
2232	   (string :tag "Table of Contents"))))
2233
2234(defcustom org-export-default-language "en"
2235  "The default language of HTML export, as a string.
2236This should have an association in `org-export-language-setup'."
2237  :group 'org-export-general
2238  :type 'string)
2239
2240(defcustom org-export-headline-levels 3
2241  "The last level which is still exported as a headline.
2242Inferior levels will produce itemize lists when exported.
2243Note that a numeric prefix argument to an exporter function overrides
2244this setting.
2245
2246This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2247  :group 'org-export-general
2248  :type 'number)
2249
2250(defcustom org-export-with-section-numbers t
2251  "Non-nil means, add section numbers to headlines when exporting.
2252
2253This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2254  :group 'org-export-general
2255  :type 'boolean)
2256
2257(defcustom org-export-with-toc t
2258  "Non-nil means, create a table of contents in exported files.
2259The TOC contains headlines with levels up to`org-export-headline-levels'.
2260When an integer, include levels up to N in the toc, this may then be
2261different from `org-export-headline-levels', but it will not be allowed
2262to be larger than the number of headline levels.
2263When nil, no table of contents is made.
2264
2265Headlines which contain any TODO items will be marked with \"(*)\" in
2266ASCII export, and with red color in HTML output, if the option
2267`org-export-mark-todo-in-toc' is set.
2268
2269In HTML output, the TOC will be clickable.
2270
2271This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
2272or \"toc:3\"."
2273  :group 'org-export-general
2274  :type '(choice
2275	  (const :tag "No Table of Contents" nil)
2276	  (const :tag "Full Table of Contents" t)
2277	  (integer :tag "TOC to level")))
2278
2279(defcustom org-export-mark-todo-in-toc nil
2280  "Non-nil means, mark TOC lines that contain any open TODO items."
2281  :group 'org-export-general
2282  :type 'boolean)
2283
2284(defcustom org-export-preserve-breaks nil
2285  "Non-nil means, preserve all line breaks when exporting.
2286Normally, in HTML output paragraphs will be reformatted.  In ASCII
2287export, line breaks will always be preserved, regardless of this variable.
2288
2289This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2290  :group 'org-export-general
2291  :type 'boolean)
2292
2293(defcustom org-export-with-archived-trees 'headline
2294  "Whether subtrees with the ARCHIVE tag should be exported.
2295This can have three different values
2296nil       Do not export, pretend this tree is not present
2297t         Do export the entire tree
2298headline  Only export the headline, but skip the tree below it."
2299  :group 'org-export-general
2300  :group 'org-archive
2301  :type '(choice
2302	  (const :tag "not at all" nil)
2303	  (const :tag "headline only" 'headline)
2304	  (const :tag "entirely" t)))
2305
2306(defcustom org-export-with-timestamps t
2307  "If nil, do not export time stamps and associated keywords."
2308  :group 'org-export-general
2309  :type 'boolean)
2310
2311(defcustom org-export-remove-timestamps-from-toc t
2312  "If nil, remove timestamps from the table of contents entries."
2313  :group 'org-export-general
2314  :type 'boolean)
2315
2316(defcustom org-export-with-tags 'not-in-toc
2317  "If nil, do not export tags, just remove them from headlines.
2318If this is the symbol `not-in-toc', tags will be removed from table of
2319contents entries, but still be shown in the headlines of the document."
2320  :group 'org-export-general
2321  :type '(choice
2322	  (const :tag "Off" nil)
2323	  (const :tag "Not in TOC" not-in-toc)
2324	  (const :tag "On" t)))
2325
2326(defgroup org-export-translation nil
2327  "Options for translating special ascii sequences for the export backends."
2328  :tag "Org Export Translation"
2329  :group 'org-export)
2330
2331(defcustom org-export-with-emphasize t
2332  "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2333If the export target supports emphasizing text, the word will be
2334typeset in bold, italic, or underlined, respectively.  Works only for
2335single words, but you can say: I *really* *mean* *this*.
2336Not all export backends support this.
2337
2338This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2339  :group 'org-export-translation
2340  :type 'boolean)
2341
2342(defcustom org-export-with-sub-superscripts t
2343  "Non-nil means, interpret \"_\" and \"^\" for export.
2344When this option is turned on, you can use TeX-like syntax for sub- and
2345superscripts.  Several characters after \"_\" or \"^\" will be
2346considered as a single item - so grouping with {} is normally not
2347needed.  For example, the following things will be parsed as single
2348sub- or superscripts.
2349
2350 10^24   or   10^tau     several digits will be considered 1 item.
2351 10^-12  or   10^-tau    a leading sign with digits or a word
2352 x^2-y^3                 will be read as x^2 - y^3, because items are
2353			 terminated by almost any nonword/nondigit char.
2354 x_{i^2} or   x^(2-i)    braces or parenthesis do grouping.
2355
2356Still, ambiguity is possible - so when in doubt use {} to enclose the
2357sub/superscript.
2358Not all export backends support this, but HTML does.
2359
2360This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
2361  :group 'org-export-translation
2362  :type 'boolean)
2363
2364(defcustom org-export-with-TeX-macros t
2365  "Non-nil means, interpret simple TeX-like macros when exporting.
2366For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
2367No only real TeX macros will work here, but the standard HTML entities
2368for math can be used as macro names as well.  For a list of supported
2369names in HTML export, see the constant `org-html-entities'.
2370Not all export backends support this.
2371
2372This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
2373  :group 'org-export-translation
2374  :group 'org-latex
2375  :type 'boolean)
2376
2377(defcustom org-export-with-LaTeX-fragments nil
2378  "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
2379When set, the exporter will find LaTeX environments if the \\begin line is
2380the first non-white thing on a line.  It will also find the math delimiters
2381like $a=b$ and \\( a=b \\) for inline math,  $$a=b$$ and \\[ a=b \\] for
2382display math.
2383
2384This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
2385  :group 'org-export-translation
2386  :group 'org-latex
2387  :type 'boolean)
2388
2389(defcustom org-export-with-fixed-width t
2390  "Non-nil means, lines starting with \":\" will be in fixed width font.
2391This can be used to have pre-formatted text, fragments of code etc.  For
2392example:
2393  : ;; Some Lisp examples
2394  : (while (defc cnt)
2395  :   (ding))
2396will be looking just like this in also HTML.  See also the QUOTE keyword.
2397Not all export backends support this.
2398
2399This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2400  :group 'org-export-translation
2401  :type 'boolean)
2402
2403(defcustom org-match-sexp-depth 3
2404  "Number of stacked braces for sub/superscript matching.
2405This has to be set before loading org.el to be effective."
2406  :group 'org-export-translation
2407  :type 'integer)
2408
2409(defgroup org-export-tables nil
2410  "Options for exporting tables in Org-mode."
2411  :tag "Org Export Tables"
2412  :group 'org-export)
2413
2414(defcustom org-export-with-tables t
2415  "If non-nil, lines starting with \"|\" define a table.
2416For example:
2417
2418  | Name        | Address  | Birthday  |
2419  |-------------+----------+-----------|
2420  | Arthur Dent | England  | 29.2.2100 |
2421
2422Not all export backends support this.
2423
2424This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2425  :group 'org-export-tables
2426  :type 'boolean)
2427
2428(defcustom org-export-highlight-first-table-line t
2429  "Non-nil means, highlight the first table line.
2430In HTML export, this means use <th> instead of <td>.
2431In tables created with table.el, this applies to the first table line.
2432In Org-mode tables, all lines before the first horizontal separator
2433line will be formatted with <th> tags."
2434  :group 'org-export-tables
2435  :type 'boolean)
2436
2437(defcustom org-export-table-remove-special-lines t
2438  "Remove special lines and marking characters in calculating tables.
2439This removes the special marking character column from tables that are set
2440up for spreadsheet calculations.  It also removes the entire lines
2441marked with `!', `_', or `^'.  The lines with `$' are kept, because
2442the values of constants may be useful to have."
2443  :group 'org-export-tables
2444  :type 'boolean)
2445
2446(defcustom org-export-prefer-native-exporter-for-tables nil
2447  "Non-nil means, always export tables created with table.el natively.
2448Natively means, use the HTML code generator in table.el.
2449When nil, Org-mode's own HTML generator is used when possible (i.e. if
2450the table does not use row- or column-spanning).  This has the
2451advantage, that the automatic HTML conversions for math symbols and
2452sub/superscripts can be applied.  Org-mode's HTML generator is also
2453much faster."
2454  :group 'org-export-tables
2455  :type 'boolean)
2456
2457(defgroup org-export-ascii nil
2458  "Options specific for ASCII export of Org-mode files."
2459  :tag "Org Export ASCII"
2460  :group 'org-export)
2461
2462(defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2463  "Characters for underlining headings in ASCII export.
2464In the given sequence, these characters will be used for level 1, 2, ..."
2465  :group 'org-export-ascii
2466  :type '(repeat character))
2467
2468(defcustom org-export-ascii-bullets '(?* ?+ ?-)
2469  "Bullet characters for headlines converted to lists in ASCII export.
2470The first character is is used for the first lest level generated in this
2471way, and so on.  If there are more levels than characters given here,
2472the list will be repeated.
2473Note that plain lists will keep the same bullets as the have in the
2474Org-mode file."
2475  :group 'org-export-ascii
2476  :type '(repeat character))
2477
2478(defgroup org-export-xml nil
2479  "Options specific for XML export of Org-mode files."
2480  :tag "Org Export XML"
2481  :group 'org-export)
2482
2483(defgroup org-export-html nil
2484  "Options specific for HTML export of Org-mode files."
2485  :tag "Org Export HTML"
2486  :group 'org-export)
2487
2488(defcustom org-export-html-style
2489"<style type=\"text/css\">
2490  html {
2491	font-family: Times, serif;
2492	font-size: 12pt;
2493  }
2494  .title { text-align: center; }
2495  .todo  { color: red; }
2496  .done { color: green; }
2497  .timestamp { color: grey }
2498  .timestamp-kwd { color: CadetBlue }
2499  .tag { background-color:lightblue; font-weight:normal }
2500  .target { background-color: lavender; }
2501  pre {
2502	border: 1pt solid #AEBDCC;
2503	background-color: #F3F5F7;
2504	padding: 5pt;
2505	font-family: courier, monospace;
2506  }
2507  table { border-collapse: collapse; }
2508  td, th {
2509	vertical-align: top;
2510	<!--border: 1pt solid #ADB9CC;-->
2511  }
2512</style>"
2513  "The default style specification for exported HTML files.
2514Since there are different ways of setting style information, this variable
2515needs to contain the full HTML structure to provide a style, including the
2516surrounding HTML tags.  The style specifications should include definitions
2517for new classes todo, done, title, and deadline.  For example, legal values
2518would be:
2519
2520   <style type=\"text/css\">
2521       p { font-weight: normal; color: gray; }
2522       h1 { color: black; }
2523      .title { text-align: center; }
2524      .todo, .deadline { color: red; }
2525      .done { color: green; }
2526   </style>
2527
2528or, if you want to keep the style in a file,
2529
2530   <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2531
2532As the value of this option simply gets inserted into the HTML <head> header,
2533you can \"misuse\" it to add arbitrary text to the header."
2534  :group 'org-export-html
2535  :type 'string)
2536
2537(defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2538  "Format for typesetting the document title in HTML export."
2539  :group 'org-export-html
2540  :type 'string)
2541
2542(defcustom org-export-html-toplevel-hlevel 2
2543  "The <H> level for level 1 headings in HTML export."
2544  :group 'org-export-html
2545  :type 'string)
2546
2547(defcustom org-export-html-link-org-files-as-html t
2548  "Non-nil means, make file links to `file.org' point to `file.html'.
2549When org-mode is exporting an org-mode file to HTML, links to
2550non-html files are directly put into a href tag in HTML.
2551However, links to other Org-mode files (recognized by the
2552extension `.org.) should become links to the corresponding html
2553file, assuming that the linked org-mode file will also be
2554converted to HTML.
2555When nil, the links still point to the plain `.org' file."
2556  :group 'org-export-html
2557  :type 'boolean)
2558
2559(defcustom org-export-html-inline-images 'maybe
2560  "Non-nil means, inline images into exported HTML pages.
2561This is done using an <img> tag.  When nil, an anchor with href is used to
2562link to the image.  If this option is `maybe', then images in links with
2563an empty description will be inlined, while images with a description will
2564be linked only."
2565  :group 'org-export-html
2566  :type '(choice (const :tag "Never" nil)
2567		 (const :tag "Always" t)
2568		 (const :tag "When there is no description" maybe)))
2569
2570;; FIXME: rename
2571(defcustom org-export-html-expand t
2572  "Non-nil means, for HTML export, treat @<...> as HTML tag.
2573When nil, these tags will be exported as plain text and therefore
2574not be interpreted by a browser.
2575
2576This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2577  :group 'org-export-html
2578  :type 'boolean)
2579
2580(defcustom org-export-html-table-tag
2581  "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
2582  "The HTML tag used to start a table.
2583This must be a <table> tag, but you may change the options like
2584borders and spacing."
2585  :group 'org-export-html
2586  :type 'string)
2587
2588(defcustom org-export-html-with-timestamp nil
2589  "If non-nil, write `org-export-html-html-helper-timestamp'
2590into the exported HTML text.  Otherwise, the buffer will just be saved
2591to a file."
2592  :group 'org-export-html
2593  :type 'boolean)
2594
2595(defcustom org-export-html-html-helper-timestamp
2596  "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2597  "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2598  :group 'org-export-html
2599  :type 'string)
2600
2601(defgroup org-export-icalendar nil
2602  "Options specific for iCalendar export of Org-mode files."
2603  :tag "Org Export iCalendar"
2604  :group 'org-export)
2605
2606(defcustom org-combined-agenda-icalendar-file "~/org.ics"
2607  "The file name for the iCalendar file covering all agenda files.
2608This file is created with the command \\[org-export-icalendar-all-agenda-files].
2609The file name should be absolute."
2610  :group 'org-export-icalendar
2611  :type 'file)
2612
2613(defcustom org-icalendar-include-todo nil
2614  "Non-nil means, export to iCalendar files should also cover TODO items."
2615  :group 'org-export-icalendar
2616  :type '(choice
2617	  (const :tag "None" nil)
2618	  (const :tag "Unfinished" t)
2619	  (const :tag "All" all)))
2620
2621(defcustom org-icalendar-combined-name "OrgMode"
2622  "Calendar name for the combined iCalendar representing all agenda files."
2623  :group 'org-export-icalendar
2624  :type 'string)
2625
2626(defgroup org-font-lock nil
2627  "Font-lock settings for highlighting in Org-mode."
2628  :tag "Org Font Lock"
2629  :group 'org)
2630
2631(defcustom org-level-color-stars-only nil
2632  "Non-nil means fontify only the stars in each headline.
2633When nil, the entire headline is fontified.
2634Changing it requires restart of `font-lock-mode' to become effective
2635also in regions already fontified."
2636  :group 'org-font-lock
2637  :type 'boolean)
2638
2639(defcustom org-hide-leading-stars nil
2640  "Non-nil means, hide the first N-1 stars in a headline.
2641This works by using the face `org-hide' for these stars.  This
2642face is white for a light background, and black for a dark
2643background.  You may have to customize the face `org-hide' to
2644make this work.
2645Changing it requires restart of `font-lock-mode' to become effective
2646also in regions already fontified.
2647You may also set this on a per-file basis by adding one of the following
2648lines to the buffer:
2649
2650   #+STARTUP: hidestars
2651   #+STARTUP: showstars"
2652  :group 'org-font-lock
2653  :type 'boolean)
2654
2655(defcustom org-fontify-done-headline nil
2656  "Non-nil means, change the face of a headline if it is marked DONE.
2657Normally, only the TODO/DONE keyword indicates the state of a headline.
2658When this is non-nil, the headline after the keyword is set to the
2659`org-headline-done' as an additional indication."
2660  :group 'org-font-lock
2661  :type 'boolean)
2662
2663(defcustom org-fontify-emphasized-text t
2664  "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2665Changing this variable requires a restart of Emacs to take effect."
2666  :group 'org-font-lock
2667  :type 'boolean)
2668
2669(defvar org-emph-re nil
2670  "Regular expression for matching emphasis.")
2671(defvar org-emphasis-regexp-components) ; defined just below
2672(defvar org-emphasis-alist) ; defined just below
2673(defun org-set-emph-re (var val)
2674  "Set variable and compute the emphasis regular expression."
2675  (set var val)
2676  (when (and (boundp 'org-emphasis-alist)
2677	     (boundp 'org-emphasis-regexp-components)
2678	     org-emphasis-alist org-emphasis-regexp-components)
2679    (let* ((e org-emphasis-regexp-components)
2680	   (pre (car e))
2681	   (post (nth 1 e))
2682	   (border (nth 2 e))
2683	   (body (nth 3 e))
2684	   (nl (nth 4 e))
2685	   (stacked (nth 5 e))
2686	   (body1 (concat body "*?"))
2687	   (markers (mapconcat 'car org-emphasis-alist "")))
2688      ;; make sure special characters appear at the right position in the class
2689      (if (string-match "\\^" markers)
2690	  (setq markers (concat (replace-match "" t t markers) "^")))
2691      (if (string-match "-" markers)
2692	  (setq markers (concat (replace-match "" t t markers) "-")))
2693;      (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2694;      (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\\(?:\n?" body "*?\\)?")))
2695      (if (> nl 0)
2696          (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2697                              (int-to-string nl) "\\}")))
2698      ;; Make the regexp
2699      (setq org-emph-re
2700	    (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2701		    "\\("
2702		    "\\([" markers "]\\)"
2703		    "\\("
2704		    "[^" border markers "]"
2705		    body1
2706		    "[^" border markers "]"
2707		    "\\)"
2708		    "\\3\\)"
2709		    "\\([" post (if stacked markers) "]\\|$\\)")))))
2710
2711(defcustom org-emphasis-regexp-components
2712  '(" \t('\"" " \t.,?;'\")" " \t\r\n," "." 1 nil)
2713  "Components used to build the reqular expression for emphasis.
2714This is a list with 6 entries.  Terminology:  In an emphasis string
2715like \" *strong word* \", we call the initial space PREMATCH, the final
2716space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2717and \"trong wor\" is the body.  The different components in this variable
2718specify what is allowed/forbidden in each part:
2719
2720pre          Chars allowed as prematch.  Beginning of line will be allowed too.
2721post         Chars allowed as postmatch.  End of line will be allowed too.
2722border       The chars *forbidden* as border characters.  In addition to the
2723             characters given here, all marker characters are forbidden too.
2724body-regexp  A regexp like \".\" to match a body character.  Don't use
2725             non-shy groups here, and don't allow newline here.
2726newline      The maximum number of newlines allowed in an emphasis exp.
2727stacked      Non-nil means, allow stacked styles.  This works only in HTML
2728             export.  When this is set, all marker characters (as given in
2729             `org-emphasis-alist') will be allowed as pre/post, aiding
2730             inside-out matching.
2731Use customize to modify this, or restart Emacs after changing it."
2732  :group 'org-font-lock
2733  :set 'org-set-emph-re
2734  :type '(list
2735	  (sexp    :tag "Allowed chars in pre      ")
2736	  (sexp    :tag "Allowed chars in post     ")
2737	  (sexp    :tag "Forbidden chars in border ")
2738	  (sexp    :tag "Regexp for body           ")
2739	  (integer :tag "number of newlines allowed")
2740	  (boolean :tag "Stacking allowed          ")))
2741
2742(defcustom org-emphasis-alist
2743  '(("*" bold "<b>" "</b>")
2744    ("/" italic "<i>" "</i>")
2745    ("_" underline "<u>" "</u>")
2746    ("=" shadow "<code>" "</code>")
2747    ("+" (:strike-through t) "<del>" "</del>")
2748)
2749"Special syntax for emphasized text.
2750Text starting and ending with a special character will be emphasized, for
2751example *bold*, _underlined_ and /italic/.  This variable sets the marker
2752characters, the face to bbe used by font-lock for highlighting in Org-mode
2753Emacs buffers, and the HTML tags to be used for this.
2754Use customize to modify this, or restart Emacs after changing it."
2755  :group 'org-font-lock
2756  :set 'org-set-emph-re
2757  :type '(repeat
2758	  (list
2759	   (string :tag "Marker character")
2760	   (choice
2761	    (face :tag "Font-lock-face")
2762	    (plist :tag "Face property list"))
2763	   (string :tag "HTML start tag")
2764	   (string :tag "HTML end tag"))))
2765
2766;;; The faces
2767
2768(defgroup org-faces nil
2769  "Faces in Org-mode."
2770  :tag "Org Faces"
2771  :group 'org-font-lock)
2772
2773(defun org-compatible-face (specs)
2774  "Make a compatible face specification.
2775XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2776For them we convert a (min-colors 8) entry to a `tty' entry and move it
2777to the top of the list.  The `min-colors' attribute will be removed from
2778any other entries, and any resulting duplicates will be removed entirely."
2779  (if (or (featurep 'xemacs) (< emacs-major-version 22))
2780      (let (r e a)
2781	(while (setq e (pop specs))
2782	  (cond
2783	   ((memq (car e) '(t default)) (push e r))
2784	   ((setq a (member '(min-colors 8) (car e)))
2785	    (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2786				 (cdr e)))))
2787	   ((setq a (assq 'min-colors (car e)))
2788	    (setq e (cons (delq a (car e)) (cdr e)))
2789	    (or (assoc (car e) r) (push e r)))
2790	   (t (or (assoc (car e) r) (push e r)))))
2791	(nreverse r))
2792    specs))
2793
2794(defface org-hide
2795  '((((background light)) (:foreground "white"))
2796    (((background dark)) (:foreground "black")))
2797  "Face used to hide leading stars in headlines.
2798The forground color of this face should be equal to the background
2799color of the frame."
2800  :group 'org-faces)
2801
2802(defface org-level-1 ;; font-lock-function-name-face
2803  (org-compatible-face
2804   '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2805     (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2806     (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2807     (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2808     (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2809     (t (:bold t))))
2810  "Face used for level 1 headlines."
2811  :group 'org-faces)
2812
2813(defface org-level-2 ;; font-lock-variable-name-face
2814  (org-compatible-face
2815   '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2816     (((class color) (min-colors 16) (background dark))  (:foreground "LightGoldenrod"))
2817     (((class color) (min-colors 8)  (background light)) (:foreground "yellow"))
2818     (((class color) (min-colors 8)  (background dark))  (:foreground "yellow" :bold t))
2819     (t (:bold t))))
2820  "Face used for level 2 headlines."
2821  :group 'org-faces)
2822
2823(defface org-level-3 ;; font-lock-keyword-face
2824  (org-compatible-face
2825   '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2826     (((class color) (min-colors 88) (background dark))  (:foreground "Cyan1"))
2827     (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2828     (((class color) (min-colors 16) (background dark))  (:foreground "Cyan"))
2829     (((class color) (min-colors 8)  (background light)) (:foreground "purple" :bold t))
2830     (((class color) (min-colors 8)  (background dark))  (:foreground "cyan" :bold t))
2831     (t (:bold t))))
2832  "Face used for level 3 headlines."
2833  :group 'org-faces)
2834
2835(defface org-level-4   ;; font-lock-comment-face
2836  (org-compatible-face
2837   '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2838     (((class color) (min-colors 88) (background dark))  (:foreground "chocolate1"))
2839     (((class color) (min-colors 16) (background light)) (:foreground "red"))
2840     (((class color) (min-colors 16) (background dark))  (:foreground "red1"))
2841     (((class color) (min-colors 8) (background light))  (:foreground "red" :bold t))
2842     (((class color) (min-colors 8) (background dark))   (:foreground "red" :bold t))
2843     (t (:bold t))))
2844  "Face used for level 4 headlines."
2845  :group 'org-faces)
2846
2847(defface org-level-5 ;; font-lock-type-face
2848  (org-compatible-face
2849   '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2850     (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2851     (((class color) (min-colors 8)) (:foreground "green"))))
2852  "Face used for level 5 headlines."
2853  :group 'org-faces)
2854
2855(defface org-level-6 ;; font-lock-constant-face
2856  (org-compatible-face
2857   '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2858     (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2859     (((class color) (min-colors 8)) (:foreground "magenta"))))
2860  "Face used for level 6 headlines."
2861  :group 'org-faces)
2862
2863(defface org-level-7 ;; font-lock-builtin-face
2864  (org-compatible-face
2865   '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2866     (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2867     (((class color) (min-colors 8)) (:foreground "blue"))))
2868  "Face used for level 7 headlines."
2869  :group 'org-faces)
2870
2871(defface org-level-8 ;; font-lock-string-face
2872  (org-compatible-face
2873   '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2874     (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2875     (((class color) (min-colors 8)) (:foreground "green"))))
2876  "Face used for level 8 headlines."
2877  :group 'org-faces)
2878
2879(defface org-special-keyword ;; font-lock-string-face
2880  (org-compatible-face
2881   '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2882     (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2883     (t (:italic t))))
2884  "Face used for special keywords."
2885  :group 'org-faces)
2886
2887(defface org-warning ;; font-lock-warning-face
2888  (org-compatible-face
2889   '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2890     (((class color) (min-colors 16) (background dark))  (:foreground "Pink" :bold t))
2891     (((class color) (min-colors 8)  (background light)) (:foreground "red"  :bold t))
2892     (((class color) (min-colors 8)  (background dark))  (:foreground "red"  :bold t))
2893     (t (:bold t))))
2894  "Face for deadlines and TODO keywords."
2895  :group 'org-faces)
2896
2897(defface org-headline-done ;; font-lock-string-face
2898  (org-compatible-face
2899   '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2900     (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2901     (((class color) (min-colors 8)  (background light)) (:bold nil))))
2902  "Face used to indicate that a headline is DONE.
2903This face is only used if `org-fontify-done-headline' is set."
2904  :group 'org-faces)
2905
2906(defface org-archived    ; similar to shadow
2907  (org-compatible-face
2908   '((((class color grayscale) (min-colors 88) (background light))
2909      (:foreground "grey50"))
2910     (((class color grayscale) (min-colors 88) (background dark))
2911      (:foreground "grey70"))
2912     (((class color) (min-colors 8) (background light))
2913      (:foreground "green"))
2914     (((class color) (min-colors 8) (background dark))
2915      (:foreground "yellow"))))
2916   "Face for headline with the ARCHIVE tag."
2917   :group 'org-faces)
2918
2919(defface org-link
2920  '((((class color) (background light)) (:foreground "Purple" :underline t))
2921    (((class color) (background dark)) (:foreground "Cyan" :underline t))
2922    (t (:underline t)))
2923  "Face for links."
2924  :group 'org-faces)
2925
2926(defface org-date
2927  '((((class color) (background light)) (:foreground "Purple" :underline t))
2928    (((class color) (background dark)) (:foreground "Cyan" :underline t))
2929    (t (:underline t)))
2930  "Face for links."
2931  :group 'org-faces)
2932
2933(defface org-tag
2934  '((t (:bold t)))
2935  "Face for tags."
2936  :group 'org-faces)
2937
2938(defface org-todo ;; font-lock-warning-face
2939  (org-compatible-face
2940   '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2941     (((class color) (min-colors 16) (background dark))  (:foreground "Pink" :bold t))
2942     (((class color) (min-colors 8)  (background light)) (:foreground "red"  :bold t))
2943     (((class color) (min-colors 8)  (background dark))  (:foreground "red"  :bold t))
2944     (t (:inverse-video t :bold t))))
2945  "Face for TODO keywords."
2946  :group 'org-faces)
2947
2948(defface org-done ;; font-lock-type-face
2949  (org-compatible-face
2950   '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
2951     (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
2952     (((class color) (min-colors 8)) (:foreground "green"))
2953     (t (:bold t))))
2954  "Face used for DONE."
2955  :group 'org-faces)
2956
2957(defface org-table ;; font-lock-function-name-face
2958  (org-compatible-face
2959   '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2960     (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2961     (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2962     (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2963     (((class color) (min-colors 8)  (background light)) (:foreground "blue"))
2964     (((class color) (min-colors 8)  (background dark)))))
2965  "Face used for tables."
2966  :group 'org-faces)
2967
2968(defface org-formula
2969  (org-compatible-face
2970   '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2971     (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2972     (((class color) (min-colors 8)  (background light)) (:foreground "red"))
2973     (((class color) (min-colors 8)  (background dark)) (:foreground "red"))
2974     (t (:bold t :italic t))))
2975  "Face for formulas."
2976  :group 'org-faces)
2977
2978(defface org-scheduled-today
2979  (org-compatible-face
2980   '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2981     (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2982     (((class color) (min-colors 8)) (:foreground "green"))
2983     (t (:bold t :italic t))))
2984  "Face for items scheduled for a certain day."
2985  :group 'org-faces)
2986
2987(defface org-scheduled-previously
2988  (org-compatible-face
2989   '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2990     (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2991     (((class color) (min-colors 8)  (background light)) (:foreground "red"))
2992     (((class color) (min-colors 8)  (background dark)) (:foreground "red" :bold t))
2993     (t (:bold t))))
2994  "Face for items scheduled previously, and not yet done."
2995  :group 'org-faces)
2996
2997(defface org-upcoming-deadline
2998  (org-compatible-face
2999   '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3000     (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3001     (((class color) (min-colors 8)  (background light)) (:foreground "red"))
3002     (((class color) (min-colors 8)  (background dark)) (:foreground "red" :bold t))
3003     (t (:bold t))))
3004  "Face for items scheduled previously, and not yet done."
3005  :group 'org-faces)
3006
3007(defface org-time-grid ;; font-lock-variable-name-face
3008  (org-compatible-face
3009   '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3010     (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3011     (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
3012  "Face used for time grids."
3013  :group 'org-faces)
3014
3015(defconst org-level-faces
3016  '(org-level-1 org-level-2 org-level-3 org-level-4
3017    org-level-5 org-level-6 org-level-7 org-level-8
3018    ))
3019(defconst org-n-levels (length org-level-faces))
3020
3021
3022;;; Variables for pre-computed regular expressions, all buffer local
3023
3024(defvar org-done-string nil
3025  "The last string in `org-todo-keywords', indicating an item is DONE.")
3026(make-variable-buffer-local 'org-done-string)
3027(defvar org-todo-regexp nil
3028  "Matches any of the TODO state keywords.")
3029(make-variable-buffer-local 'org-todo-regexp)
3030(defvar org-not-done-regexp nil
3031  "Matches any of the TODO state keywords except the last one.")
3032(make-variable-buffer-local 'org-not-done-regexp)
3033(defvar org-todo-line-regexp nil
3034  "Matches a headline and puts TODO state into group 2 if present.")
3035(make-variable-buffer-local 'org-todo-line-regexp)
3036(defvar org-todo-line-tags-regexp nil
3037  "Matches a headline and puts TODO state into group 2 if present.
3038Also put tags into group 4 if tags are present.")
3039(make-variable-buffer-local 'org-todo-line-tags-regexp)
3040(defvar org-nl-done-regexp nil
3041  "Matches newline followed by a headline with the DONE keyword.")
3042(make-variable-buffer-local 'org-nl-done-regexp)
3043(defvar org-looking-at-done-regexp nil
3044  "Matches the DONE keyword a point.")
3045(make-variable-buffer-local 'org-looking-at-done-regexp)
3046(defvar org-todo-kwd-priority-p nil
3047  "Do TODO items have priorities?")
3048(make-variable-buffer-local 'org-todo-kwd-priority-p)
3049(defvar org-todo-kwd-max-priority nil
3050  "Maximum priority of TODO items.")
3051(make-variable-buffer-local 'org-todo-kwd-max-priority)
3052(defvar org-ds-keyword-length 12
3053  "Maximum length of the Deadline and SCHEDULED keywords.")
3054(make-variable-buffer-local 'org-ds-keyword-length)
3055(defvar org-deadline-regexp nil
3056  "Matches the DEADLINE keyword.")
3057(make-variable-buffer-local 'org-deadline-regexp)
3058(defvar org-deadline-time-regexp nil
3059  "Matches the DEADLINE keyword together with a time stamp.")
3060(make-variable-buffer-local 'org-deadline-time-regexp)
3061(defvar org-deadline-line-regexp nil
3062  "Matches the DEADLINE keyword and the rest of the line.")
3063(make-variable-buffer-local 'org-deadline-line-regexp)
3064(defvar org-scheduled-regexp nil
3065  "Matches the SCHEDULED keyword.")
3066(make-variable-buffer-local 'org-scheduled-regexp)
3067(defvar org-scheduled-time-regexp nil
3068  "Matches the SCHEDULED keyword together with a time stamp.")
3069(make-variable-buffer-local 'org-scheduled-time-regexp)
3070(defvar org-closed-time-regexp nil
3071  "Matches the CLOSED keyword together with a time stamp.")
3072(make-variable-buffer-local 'org-closed-time-regexp)
3073
3074(defvar org-keyword-time-regexp nil
3075  "Matches any of the 4 keywords, together with the time stamp.")
3076(make-variable-buffer-local 'org-keyword-time-regexp)
3077(defvar org-keyword-time-not-clock-regexp nil
3078  "Matches any of the 3 keywords, together with the time stamp.")
3079(make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3080(defvar org-maybe-keyword-time-regexp nil
3081  "Matches a timestamp, possibly preceeded by a keyword.")
3082(make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3083
3084(defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
3085				   rear-nonsticky t mouse-map t fontified t)
3086  "Properties to remove when a string without properties is wanted.")
3087
3088(defsubst org-match-string-no-properties (num &optional string)
3089  (if (featurep 'xemacs)
3090      (let ((s (match-string num string)))
3091	(remove-text-properties 0 (length s) org-rm-props s)
3092	s)
3093    (match-string-no-properties num string)))
3094
3095(defsubst org-no-properties (s)
3096  (remove-text-properties 0 (length s) org-rm-props s)
3097  s)
3098
3099(defsubst org-get-alist-option (option key)
3100  (cond ((eq key t) t)
3101	((eq option t) t)
3102	((assoc key option) (cdr (assoc key option)))
3103	(t (cdr (assq 'default option)))))
3104
3105(defsubst org-set-local (var value)
3106  "Make VAR local in current buffer and set it to VALUE."
3107  (set (make-variable-buffer-local var) value))
3108
3109(defsubst org-mode-p ()
3110  "Check if the current buffer is in Org-mode."
3111  (eq major-mode 'org-mode))
3112
3113(defsubst org-last (list)
3114  "Return the last element of LIST."
3115  (car (last list)))
3116
3117(defun org-let (list &rest body)
3118  (eval (cons 'let (cons list body))))
3119(put 'org-let 'lisp-indent-function 1)
3120
3121(defun org-let2 (list1 list2 &rest body)
3122  (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
3123(put 'org-let2 'lisp-indent-function 2)
3124(defconst org-startup-options
3125  '(("fold" org-startup-folded t)
3126    ("overview" org-startup-folded t)
3127    ("nofold" org-startup-folded nil)
3128    ("showall" org-startup-folded nil)
3129    ("content" org-startup-folded content)
3130    ("hidestars" org-hide-leading-stars t)
3131    ("showstars" org-hide-leading-stars nil)
3132    ("odd" org-odd-levels-only t)
3133    ("oddeven" org-odd-levels-only nil)
3134    ("align" org-startup-align-all-tables t)
3135    ("noalign" org-startup-align-all-tables nil)
3136    ("customtime" org-display-custom-times t)
3137    ("logging" org-log-done t)
3138    ("logdone" org-log-done t)
3139    ("nologging" org-log-done nil)
3140    ("lognotedone" org-log-done done push)
3141    ("lognotestate" org-log-done state push)
3142    ("lognoteclock-out" org-log-done clock-out push))
3143  "Variable associated with STARTUP options for org-mode.
3144Each element is a list of three items: The startup options as written
3145in the #+STARTUP line, the corresponding variable, and the value to
3146set this variable to if the option is found.  An optional forth element PUSH
3147means to push this value onto the list in the variable.")
3148
3149(defun org-set-regexps-and-options ()
3150  "Precompute regular expressions for current buffer."
3151  (when (org-mode-p)
3152    (let ((re (org-make-options-regexp
3153	       '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
3154		 "STARTUP" "ARCHIVE" "TAGS" "LINK")))
3155	  (splitre "[ \t]+")
3156	  kwds int key value cat arch tags links)
3157      (save-excursion
3158	(save-restriction
3159	  (widen)
3160	  (goto-char (point-min))
3161	  (while (re-search-forward re nil t)
3162	    (setq key (match-string 1) value (org-match-string-no-properties 2))
3163	    (cond
3164	     ((equal key "CATEGORY")
3165	      (if (string-match "[ \t]+$" value)
3166		  (setq value (replace-match "" t t value)))
3167	      (setq cat (intern value)))
3168	     ((equal key "SEQ_TODO")
3169	      (setq int 'sequence
3170		    kwds (append kwds (org-split-string value splitre))))
3171	     ((equal key "PRI_TODO")
3172	      (setq int 'priority
3173		    kwds (append kwds (org-split-string value splitre))))
3174	     ((equal key "TYP_TODO")
3175	      (setq int 'type
3176		    kwds (append kwds (org-split-string value splitre))))
3177	     ((equal key "TAGS")
3178	      (setq tags (append tags (org-split-string value splitre))))
3179	     ((equal key "LINK")
3180	      (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3181		(push (cons (match-string 1 value)
3182			    (org-trim (match-string 2 value)))
3183		      links)))
3184	     ((equal key "STARTUP")
3185	      (let ((opts (org-split-string value splitre))
3186		    l var val)
3187		(while (setq l (assoc (pop opts) org-startup-options))
3188		  (setq var (nth 1 l) val (nth 2 l))
3189		  (if (not (nth 3 l))
3190		      (set (make-local-variable var) val)
3191		    (if (not (listp (symbol-value var)))
3192			(set (make-local-variable var) nil))
3193		    (set (make-local-variable var) (symbol-value var))
3194		    (add-to-list var val)))))
3195	     ((equal key "ARCHIVE")
3196	      (string-match " *$" value)
3197	      (setq arch (replace-match "" t t value))
3198	      (remove-text-properties 0 (length arch)
3199				      '(face t fontified t) arch)))
3200	    )))
3201      (and cat (org-set-local 'org-category cat))
3202      (and kwds (org-set-local 'org-todo-keywords kwds))
3203      (and arch (org-set-local 'org-archive-location arch))
3204      (and int (org-set-local 'org-todo-interpretation int))
3205      (and links (setq org-link-abbrev-alist-local (nreverse links)))
3206      (when tags
3207	(let (e tgs)
3208	  (while (setq e (pop tags))
3209	    (cond
3210	     ((equal e "{") (push '(:startgroup) tgs))
3211	     ((equal e "}") (push '(:endgroup) tgs))
3212	     ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
3213	      (push (cons (match-string 1 e)
3214			  (string-to-char (match-string 2 e)))
3215		    tgs))
3216	     (t (push (list e) tgs))))
3217	  (org-set-local 'org-tag-alist nil)
3218	  (while (setq e (pop tgs))
3219	    (or (and (stringp (car e))
3220		     (assoc (car e) org-tag-alist))
3221		(push e org-tag-alist))))))
3222
3223    ;; Compute the regular expressions and other local variables
3224    (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
3225	  org-todo-kwd-max-priority (1- (length org-todo-keywords))
3226	  org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3227					  (length org-scheduled-string)))
3228	  org-done-string
3229	  (nth (1- (length org-todo-keywords)) org-todo-keywords)
3230	  org-todo-regexp
3231	  (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
3232				      "\\|") "\\)\\>")
3233	  org-not-done-regexp
3234	  (concat "\\<\\("
3235		  (mapconcat 'regexp-quote
3236			     (nreverse (cdr (reverse org-todo-keywords)))
3237			     "\\|")
3238		  "\\)\\>")
3239	  org-todo-line-regexp
3240	  (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3241		  (mapconcat 'regexp-quote org-todo-keywords "\\|")
3242		  "\\)\\>\\)? *\\(.*\\)")
3243	  org-nl-done-regexp
3244	  (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
3245	  org-todo-line-tags-regexp
3246	  (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3247		  (mapconcat 'regexp-quote org-todo-keywords "\\|")
3248		  "\\)\\>\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
3249	  org-looking-at-done-regexp (concat "^" org-done-string "\\>")
3250	  org-deadline-regexp (concat "\\<" org-deadline-string)
3251	  org-deadline-time-regexp
3252	  (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3253	  org-deadline-line-regexp
3254	  (concat "\\<\\(" org-deadline-string "\\).*")
3255	  org-scheduled-regexp
3256	  (concat "\\<" org-scheduled-string)
3257	  org-scheduled-time-regexp
3258	  (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3259	  org-closed-time-regexp
3260	  (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3261	  org-keyword-time-regexp
3262	  (concat "\\<\\(" org-scheduled-string
3263		  "\\|" org-deadline-string
3264		  "\\|" org-closed-string
3265		  "\\|" org-clock-string "\\)"
3266		  " *[[<]\\([^]>]+\\)[]>]")
3267	  org-keyword-time-not-clock-regexp
3268	  (concat "\\<\\(" org-scheduled-string
3269		  "\\|" org-deadline-string
3270		  "\\|" org-closed-string "\\)"
3271		  " *[[<]\\([^]>]+\\)[]>]")
3272	  org-maybe-keyword-time-regexp
3273	  (concat "\\(\\<\\(" org-scheduled-string
3274		  "\\|" org-deadline-string
3275		  "\\|" org-closed-string
3276		  "\\|" org-clock-string "\\)\\)?"
3277		  " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
3278
3279    (org-set-font-lock-defaults)))
3280
3281
3282;;; Some variables ujsed in various places
3283
3284(defvar org-window-configuration nil
3285  "Used in various places to store a window configuration.")
3286(defvar org-finish-function nil
3287  "Function to be called when `C-c C-c' is used.
3288This is for getting out of special buffers like remember.")
3289
3290;;; Foreign variables, to inform the compiler
3291
3292;; XEmacs only
3293(defvar outline-mode-menu-heading)
3294(defvar outline-mode-menu-show)
3295(defvar outline-mode-menu-hide)
3296(defvar zmacs-regions) ; XEmacs regions
3297;; Emacs only
3298(defvar mark-active)
3299
3300;; Packages that org-mode interacts with
3301(defvar calc-embedded-close-formula)
3302(defvar calc-embedded-open-formula)
3303(defvar font-lock-unfontify-region-function)
3304(defvar org-goto-start-pos)
3305(defvar vm-message-pointer)
3306(defvar vm-folder-directory)
3307(defvar wl-summary-buffer-elmo-folder)
3308(defvar wl-summary-buffer-folder-name)
3309(defvar gnus-other-frame-object)
3310(defvar gnus-group-name)
3311(defvar gnus-article-current)
3312(defvar w3m-current-url)
3313(defvar w3m-current-title)
3314(defvar mh-progs)
3315(defvar mh-current-folder)
3316(defvar mh-show-folder-buffer)
3317(defvar mh-index-folder)
3318(defvar mh-searcher)
3319(defvar calendar-mode-map)
3320(defvar Info-current-file)
3321(defvar Info-current-node)
3322(defvar texmathp-why)
3323(defvar remember-save-after-remembering)
3324(defvar remember-data-file)
3325(defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
3326(defvar initial)    ; from remember.el, dynamically scoped in `remember-mode'
3327(defvar org-latex-regexps)
3328
3329(defvar original-date) ; dynamically scoped in calendar.el does scope this
3330
3331;; FIXME: Occasionally check by commenting these, to make sure
3332;;        no other functions uses these, forgetting to let-bind them.
3333(defvar entry)
3334(defvar state)
3335(defvar last-state)
3336(defvar date)
3337(defvar description)
3338
3339
3340;; Defined somewhere in this file, but used before definition.
3341(defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
3342(defvar org-agenda-undo-list)
3343(defvar org-agenda-pending-undo-list)
3344(defvar org-agenda-overriding-header)
3345(defvar orgtbl-mode)
3346(defvar org-html-entities)
3347(defvar org-struct-menu)
3348(defvar org-org-menu)
3349(defvar org-tbl-menu)
3350(defvar org-agenda-keymap)
3351(defvar org-category-table)
3352
3353;;;; Emacs/XEmacs compatibility
3354
3355;; Overlay compatibility functions
3356(defun org-make-overlay (beg end &optional buffer)
3357  (if (featurep 'xemacs)
3358      (make-extent beg end buffer)
3359    (make-overlay beg end buffer)))
3360(defun org-delete-overlay (ovl)
3361  (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
3362(defun org-detach-overlay (ovl)
3363  (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
3364(defun org-move-overlay (ovl beg end &optional buffer)
3365  (if (featurep 'xemacs)
3366      (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
3367    (move-overlay ovl beg end buffer)))
3368(defun org-overlay-put (ovl prop value)
3369  (if (featurep 'xemacs)
3370      (set-extent-property ovl prop value)
3371    (overlay-put ovl prop value)))
3372(defun org-overlay-display (ovl text &optional face evap)
3373  "Make overlay OVL display TEXT with face FACE."
3374  (if (featurep 'xemacs)
3375      (let ((gl (make-glyph text)))
3376	(and face (set-glyph-face gl face))
3377	(set-extent-property ovl 'invisible t)
3378	(set-extent-property ovl 'end-glyph gl))
3379    (overlay-put ovl 'display text)
3380    (if face (overlay-put ovl 'face face))
3381    (if evap (overlay-put ovl 'evaporate t))))
3382(defun org-overlay-before-string (ovl text &optional face evap)
3383  "Make overlay OVL display TEXT with face FACE."
3384  (if (featurep 'xemacs)
3385      (let ((gl (make-glyph text)))
3386	(and face (set-glyph-face gl face))
3387	(set-extent-property ovl 'begin-glyph gl))
3388    (if face (org-add-props text nil 'face face))
3389    (overlay-put ovl 'before-string text)
3390    (if evap (overlay-put ovl 'evaporate t))))
3391(defun org-overlay-get (ovl prop)
3392  (if (featurep 'xemacs)
3393      (extent-property ovl prop)
3394    (overlay-get ovl prop)))
3395(defun org-overlays-at (pos)
3396  (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
3397(defun org-overlays-in (&optional start end)
3398  (if (featurep 'xemacs)
3399      (extent-list nil start end)
3400    (overlays-in start end)))
3401(defun org-overlay-start (o)
3402  (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
3403(defun org-overlay-end (o)
3404  (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
3405(defun org-find-overlays (prop &optional pos delete)
3406  "Find all overlays specifying PROP at POS or point.
3407If DELETE is non-nil, delete all those overlays."
3408  (let ((overlays (org-overlays-at (or pos (point))))
3409	ov found)
3410    (while (setq ov (pop overlays))
3411      (if (org-overlay-get ov prop)
3412          (if delete (org-delete-overlay ov) (push ov found))))
3413    found))
3414
3415;; Region compatibility
3416
3417(defun org-add-hook (hook function &optional append local)
3418  "Add-hook, compatible with both Emacsen."
3419  (if (and local (featurep 'xemacs))
3420      (add-local-hook hook function append)
3421    (add-hook hook function append local)))
3422
3423(defvar org-ignore-region nil
3424  "To temporarily disable the active region.")
3425
3426(defun org-region-active-p ()
3427  "Is `transient-mark-mode' on and the region active?
3428Works on both Emacs and XEmacs."
3429  (if org-ignore-region
3430      nil
3431    (if (featurep 'xemacs)
3432	(and zmacs-regions (region-active-p))
3433      (and transient-mark-mode mark-active))))
3434
3435;; Invisibility compatibility
3436
3437(defun org-add-to-invisibility-spec (arg)
3438  "Add elements to `buffer-invisibility-spec'.
3439See documentation for `buffer-invisibility-spec' for the kind of elements
3440that can be added."
3441  (cond
3442   ((fboundp 'add-to-invisibility-spec)
3443    (add-to-invisibility-spec arg))
3444   ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
3445	(setq buffer-invisibility-spec (list arg)))
3446   (t
3447    (setq buffer-invisibility-spec
3448	  (cons arg buffer-invisibility-spec)))))
3449
3450(defun org-remove-from-invisibility-spec (arg)
3451  "Remove elements from `buffer-invisibility-spec'."
3452  (if (fboundp 'remove-from-invisibility-spec)
3453      (remove-from-invisibility-spec arg)
3454    (if (consp buffer-invisibility-spec)
3455	(setq buffer-invisibility-spec
3456	      (delete arg buffer-invisibility-spec)))))
3457
3458(defun org-in-invisibility-spec-p (arg)
3459  "Is ARG a member of `buffer-invisibility-spec'?"
3460  (if (consp buffer-invisibility-spec)
3461      (member arg buffer-invisibility-spec)
3462    nil))
3463
3464;;;; Define the Org-mode
3465
3466(if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3467    (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."))
3468
3469
3470;; We use a before-change function to check if a table might need
3471;; an update.
3472(defvar org-table-may-need-update t
3473  "Indicates that a table might need an update.
3474This variable is set by `org-before-change-function'.
3475`org-table-align' sets it back to nil.")
3476(defvar org-mode-map)
3477(defvar org-mode-hook nil)
3478(defvar org-inhibit-startup nil)        ; Dynamically-scoped param.
3479(defvar org-agenda-keep-modes nil)      ; Dynamically-scoped param.
3480
3481
3482;;;###autoload
3483(define-derived-mode org-mode outline-mode "Org"
3484  "Outline-based notes management and organizer, alias
3485\"Carsten's outline-mode for keeping track of everything.\"
3486
3487Org-mode develops organizational tasks around a NOTES file which
3488contains information about projects as plain text.  Org-mode is
3489implemented on top of outline-mode, which is ideal to keep the content
3490of large files well structured.  It supports ToDo items, deadlines and
3491time stamps, which magically appear in the diary listing of the Emacs
3492calendar.  Tables are easily created with a built-in table editor.
3493Plain text URL-like links connect to websites, emails (VM), Usenet
3494messages (Gnus), BBDB entries, and any files related to the project.
3495For printing and sharing of notes, an Org-mode file (or a part of it)
3496can be exported as a structured ASCII or HTML file.
3497
3498The following commands are available:
3499
3500\\{org-mode-map}"
3501
3502  ;; Get rid of Outline menus, they are not needed
3503  ;; Need to do this here because define-derived-mode sets up
3504  ;; the keymap so late.  Still, it is a waste to call this each time
3505  ;; we switch another buffer into org-mode.
3506  (if (featurep 'xemacs)
3507      (when (boundp 'outline-mode-menu-heading)
3508	;; Assume this is Greg's port, it used easymenu
3509	(easy-menu-remove outline-mode-menu-heading)
3510	(easy-menu-remove outline-mode-menu-show)
3511	(easy-menu-remove outline-mode-menu-hide))
3512    (define-key org-mode-map [menu-bar headings] 'undefined)
3513    (define-key org-mode-map [menu-bar hide] 'undefined)
3514    (define-key org-mode-map [menu-bar show] 'undefined))
3515
3516  (easy-menu-add org-org-menu)
3517  (easy-menu-add org-tbl-menu)
3518  (org-install-agenda-files-menu)
3519  (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3520  (org-add-to-invisibility-spec '(org-cwidth))
3521  (when (featurep 'xemacs)
3522    (org-set-local 'line-move-ignore-invisible t))
3523  (setq outline-regexp "\\*+")
3524  ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
3525  (setq outline-level 'org-outline-level)
3526  (when (and org-ellipsis (stringp org-ellipsis)
3527             (fboundp 'set-display-table-slot) (boundp 'buffer-display-table))
3528    (unless org-display-table
3529      (setq org-display-table (make-display-table)))
3530    (set-display-table-slot org-display-table
3531			    4 (string-to-vector org-ellipsis))
3532    (setq buffer-display-table org-display-table))
3533  (org-set-regexps-and-options)
3534  ;; Calc embedded
3535  (org-set-local 'calc-embedded-open-mode "# ")
3536  (modify-syntax-entry ?# "<")
3537  (if org-startup-truncated (setq truncate-lines t))
3538  (org-set-local 'font-lock-unfontify-region-function
3539		 'org-unfontify-region)
3540  ;; Activate before-change-function
3541  (org-set-local 'org-table-may-need-update t)
3542  (org-add-hook 'before-change-functions 'org-before-change-function nil
3543		'local)
3544  ;; Check for running clock before killing a buffer
3545  (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3546  ;; Paragraphs and auto-filling
3547  (org-set-autofill-regexps)
3548  (org-update-radio-target-regexp)
3549
3550  ;; Comment characters
3551;  (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3552  (org-set-local 'comment-padding " ")
3553
3554  ;; Make isearch reveal context
3555  (if (or (featurep 'xemacs)
3556	  (not (boundp 'outline-isearch-open-invisible-function)))
3557      ;; Emacs 21 and XEmacs make use of the hook
3558      (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3559    ;; Emacs 22 deals with this through a special variable
3560    (org-set-local 'outline-isearch-open-invisible-function
3561		   (lambda (&rest ignore) (org-show-context 'isearch))))
3562
3563  ;; If empty file that did not turn on org-mode automatically, make it to.
3564  (if (and org-insert-mode-line-in-empty-file
3565	   (interactive-p)
3566	   (= (point-min) (point-max)))
3567      (insert "    -*- mode: org -*-\n\n"))
3568
3569  (unless org-inhibit-startup
3570    (when org-startup-align-all-tables
3571      (let ((bmp (buffer-modified-p)))
3572	(org-table-map-tables 'org-table-align)
3573	(set-buffer-modified-p bmp)))
3574    (cond
3575     ((eq org-startup-folded t)
3576      (org-cycle '(4)))
3577     ((eq org-startup-folded 'content)
3578      (let ((this-command 'org-cycle) (last-command 'org-cycle))
3579	(org-cycle '(4)) (org-cycle '(4)))))))
3580
3581(defsubst org-call-with-arg (command arg)
3582  "Call COMMAND interactively, but pretend prefix are was ARG."
3583  (let ((current-prefix-arg arg)) (call-interactively command)))
3584
3585(defsubst org-current-line (&optional pos)
3586  (save-excursion
3587    (and pos (goto-char pos))
3588    (+ (if (bolp) 1 0) (count-lines 1 (point)))))
3589
3590(defun org-current-time ()
3591  "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3592  (if (> org-time-stamp-rounding-minutes 0)
3593      (let ((r org-time-stamp-rounding-minutes)
3594	    (time (decode-time)))
3595	(apply 'encode-time
3596	       (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3597		       (nthcdr 2 time))))
3598    (current-time)))
3599
3600(defun org-add-props (string plist &rest props)
3601  "Add text properties to entire string, from beginning to end.
3602PLIST may be a list of properties, PROPS are individual properties and values
3603that will be added to PLIST.  Returns the string that was modified."
3604  (add-text-properties
3605   0 (length string) (if props (append plist props) plist) string)
3606  string)
3607(put 'org-add-props 'lisp-indent-function 2)
3608
3609
3610;;;; Font-Lock stuff, including the activators
3611
3612(defvar org-mouse-map (make-sparse-keymap))
3613(define-key org-mouse-map
3614  (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3615(define-key org-mouse-map
3616  (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3617(when org-mouse-1-follows-link
3618  (define-key org-mouse-map [follow-link] 'mouse-face))
3619(when org-tab-follows-link
3620  (define-key org-mouse-map [(tab)] 'org-open-at-point)
3621  (define-key org-mouse-map "\C-i" 'org-open-at-point))
3622(when org-return-follows-link
3623  (define-key org-mouse-map [(return)] 'org-open-at-point)
3624  (define-key org-mouse-map "\C-m" 'org-open-at-point))
3625
3626(require 'font-lock)
3627
3628(defconst org-non-link-chars "]\t\n\r<>")
3629(defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3630			   "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3631(defconst org-link-re-with-space
3632  (concat
3633   "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3634   "\\([^" org-non-link-chars " ]"
3635   "[^" org-non-link-chars "]*"
3636   "[^" org-non-link-chars " ]\\)>?")
3637   "Matches a link with spaces, optional angular brackets around it.")
3638
3639(defconst org-link-re-with-space2
3640  (concat
3641   "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3642   "\\([^" org-non-link-chars " ]"
3643   "[^]\t\n\r]*"
3644   "[^" org-non-link-chars " ]\\)>?")
3645   "Matches a link with spaces, optional angular brackets around it.")
3646
3647(defconst org-angle-link-re
3648  (concat
3649   "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3650   "\\([^" org-non-link-chars " ]"
3651   "[^" org-non-link-chars "]*"
3652   "\\)>")
3653   "Matches link with angular brackets, spaces are allowed.")
3654(defconst org-plain-link-re
3655  (concat
3656   "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3657   "\\([^]\t\n\r<>,;() ]+\\)")
3658   "Matches plain link, without spaces.")
3659
3660(defconst org-bracket-link-regexp
3661  "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3662  "Matches a link in double brackets.")
3663
3664(defconst org-bracket-link-analytic-regexp
3665  (concat
3666  "\\[\\["
3667  "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3668  "\\([^]]+\\)"
3669  "\\]"
3670  "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3671  "\\]"))
3672; 1: http:
3673; 2: http
3674; 3: path
3675; 4: [desc]
3676; 5: desc
3677
3678(defconst org-any-link-re
3679  (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3680	  org-angle-link-re "\\)\\|\\("
3681	  org-plain-link-re "\\)")
3682  "Regular expression matching any link.")
3683
3684(defconst org-ts-lengths
3685  (cons (length (format-time-string (car org-time-stamp-formats)))
3686	(length (format-time-string (cdr org-time-stamp-formats))))
3687  "This holds the lengths of the two different time formats.")
3688(defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3689  "Regular expression for fast time stamp matching.")
3690(defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3691  "Regular expression for fast time stamp matching.")
3692(defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3693  "Regular expression matching time strings for analysis.")
3694(defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3695  "Regular expression matching time stamps, with groups.")
3696(defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3697  "Regular expression matching time stamps (also [..]), with groups.")
3698(defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3699  "Regular expression matching a time stamp range.")
3700(defconst org-tr-regexp-both
3701  (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3702  "Regular expression matching a time stamp range.")
3703(defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3704				 org-ts-regexp "\\)?")
3705  "Regular expression matching a time stamp or time stamp range.")
3706(defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3707				      org-ts-regexp-both "\\)?")
3708  "Regular expression matching a time stamp or time stamp range.
3709The time stamps may be either active or inactive.")
3710
3711(defvar org-emph-face nil)
3712
3713(defun org-do-emphasis-faces (limit)
3714  "Run through the buffer and add overlays to links."
3715  (if (re-search-forward org-emph-re limit t)
3716      (progn
3717	(font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3718					 'face
3719					 (nth 1 (assoc (match-string 3)
3720						       org-emphasis-alist)))
3721	(add-text-properties (match-beginning 2) (match-end 2)
3722			     '(font-lock-multiline t))
3723	(backward-char 1)
3724	t)))
3725
3726(defun org-activate-plain-links (limit)
3727  "Run through the buffer and add overlays to links."
3728  (if (re-search-forward org-plain-link-re limit t)
3729      (progn
3730	(add-text-properties (match-beginning 0) (match-end 0)
3731			     (list 'mouse-face 'highlight
3732				   'rear-nonsticky t
3733				   'keymap org-mouse-map
3734				   ))
3735	t)))
3736
3737(defun org-activate-angle-links (limit)
3738  "Run through the buffer and add overlays to links."
3739  (if (re-search-forward org-angle-link-re limit t)
3740      (progn
3741	(add-text-properties (match-beginning 0) (match-end 0)
3742			     (list 'mouse-face 'highlight
3743				   'rear-nonsticky t
3744				   'keymap org-mouse-map
3745				   ))
3746	t)))
3747
3748(defmacro org-maybe-intangible (props)
3749  "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
3750In emacs 21, invisible text is not avoided by the command loop, so the
3751intangible property is needed to make sure point skips this text.
3752In Emacs 22, this is not necessary.  The intangible text property has
3753led to problems with flyspell.  These problems are fixed in flyspell.el,
3754but we still avoid setting the property in Emacs 22 and later.
3755We use a macro so that the test can happen at compilation time."
3756  (if (< emacs-major-version 22)
3757      `(append '(intangible t) ,props)
3758    props))
3759
3760(defun org-activate-bracket-links (limit)
3761  "Run through the buffer and add overlays to bracketed links."
3762  (if (re-search-forward org-bracket-link-regexp limit t)
3763      (let* ((help (concat "LINK: "
3764			   (org-match-string-no-properties 1)))
3765	     ;; FIXME: above we should remove the escapes.
3766	     ;; but that requires another match, protecting match data,
3767	     ;; a lot of overhead for font-lock.
3768	     (ip (org-maybe-intangible
3769		  (list 'invisible 'org-link 'rear-nonsticky t
3770			'keymap org-mouse-map 'mouse-face 'highlight
3771			'help-echo help)))
3772	     (vp (list 'rear-nonsticky t
3773		       'keymap org-mouse-map 'mouse-face 'highlight
3774		       'help-echo help)))
3775	;; We need to remove the invisible property here.  Table narrowing
3776	;; may have made some of this invisible.
3777	(remove-text-properties (match-beginning 0) (match-end 0)
3778				'(invisible nil))
3779	(if (match-end 3)
3780	    (progn
3781	      (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3782	      (add-text-properties (match-beginning 3) (match-end 3) vp)
3783	      (add-text-properties (match-end 3) (match-end 0) ip))
3784	  (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3785	  (add-text-properties (match-beginning 1) (match-end 1) vp)
3786	  (add-text-properties (match-end 1) (match-end 0) ip))
3787	t)))
3788
3789(defun org-activate-dates (limit)
3790  "Run through the buffer and add overlays to dates."
3791  (if (re-search-forward org-tsr-regexp-both limit t)
3792      (progn
3793	(add-text-properties (match-beginning 0) (match-end 0)
3794			     (list 'mouse-face 'highlight
3795				   'rear-nonsticky t
3796				   'keymap org-mouse-map))
3797	(when org-display-custom-times
3798	  (if (match-end 3)
3799	      (org-display-custom-time (match-beginning 3) (match-end 3)))
3800	  (org-display-custom-time (match-beginning 1) (match-end 1)))
3801	t)))
3802
3803(defvar org-target-link-regexp nil
3804  "Regular expression matching radio targets in plain text.")
3805(defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3806  "Regular expression matching a link target.")
3807(defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3808  "Regular expression matching a link target.")
3809
3810(defun org-activate-target-links (limit)
3811  "Run through the buffer and add overlays to target matches."
3812  (when org-target-link-regexp
3813    (let ((case-fold-search t))
3814      (if (re-search-forward org-target-link-regexp limit t)
3815	  (progn
3816	    (add-text-properties (match-beginning 0) (match-end 0)
3817				 (list 'mouse-face 'highlight
3818				       'rear-nonsticky t
3819				       'keymap org-mouse-map
3820				       'help-echo "Radio target link"
3821				       'org-linked-text t))
3822	    t)))))
3823
3824(defun org-update-radio-target-regexp ()
3825  "Find all radio targets in this file and update the regular expression."
3826  (interactive)
3827  (when (memq 'radio org-activate-links)
3828    (setq org-target-link-regexp
3829	  (org-make-target-link-regexp (org-all-targets 'radio)))
3830    (org-restart-font-lock)))
3831
3832(defun org-hide-wide-columns (limit)
3833  (let (s e)
3834    (setq s (text-property-any (point) (or limit (point-max))
3835			       'org-cwidth t))
3836    (when s
3837      (setq e (next-single-property-change s 'org-cwidth))
3838      (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3839      (goto-char e)
3840      t)))
3841
3842(defun org-restart-font-lock ()
3843  "Restart font-lock-mode, to force refontification."
3844  (when (and (boundp 'font-lock-mode) font-lock-mode)
3845    (font-lock-mode -1)
3846    (font-lock-mode 1)))
3847
3848(defun org-all-targets (&optional radio)
3849  "Return a list of all targets in this file.
3850With optional argument RADIO, only find radio targets."
3851  (let ((re (if radio org-radio-target-regexp org-target-regexp))
3852	rtn)
3853    (save-excursion
3854      (goto-char (point-min))
3855      (while (re-search-forward re nil t)
3856	(add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3857      rtn)))
3858
3859(defun org-make-target-link-regexp (targets)
3860  "Make regular expression matching all strings in TARGETS.
3861The regular expression finds the targets also if there is a line break
3862between words."
3863  (and targets
3864       (concat
3865	"\\<\\("
3866	(mapconcat
3867	 (lambda (x)
3868	   (while (string-match " +" x)
3869	     (setq x (replace-match "\\s-+" t t x)))
3870	   x)
3871	 targets
3872	 "\\|")
3873	"\\)\\>")))
3874
3875(defun org-activate-tags (limit)
3876  (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3877      (progn
3878	(add-text-properties (match-beginning 1) (match-end 1)
3879			     (list 'mouse-face 'highlight
3880				   'rear-nonsticky t
3881				   'keymap org-mouse-map))
3882	t)))
3883
3884(defun org-font-lock-level ()
3885  (save-excursion
3886    (org-back-to-heading t)
3887    (- (match-end 0) (match-beginning 0))))
3888
3889(defun org-outline-level ()
3890  (save-excursion
3891    (looking-at outline-regexp)
3892    (if (match-beginning 1)
3893	(+ (org-get-string-indentation (match-string 1)) 1000)
3894      (- (match-end 0) (match-beginning 0)))))
3895
3896(defvar org-font-lock-keywords nil)
3897
3898(defun org-set-font-lock-defaults ()
3899  (let* ((em org-fontify-emphasized-text)
3900	 (lk org-activate-links)
3901	 (org-font-lock-extra-keywords
3902	  ;; Headlines
3903	  (list
3904	   '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3905	     (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3906	   '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3907	     (1 'org-table))
3908	   ;; Links
3909	   (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3910	   (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3911	   (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3912	   (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3913	   (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3914	   (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3915	   '(org-hide-wide-columns (0 nil append))
3916	   ;; TODO lines
3917	   (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3918		 '(1 'org-todo t))
3919	   ;; Priorities
3920	   (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3921	   ;; Special keywords
3922	   (list org-repeat-re  '(0 'org-special-keyword t))
3923	   (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3924	   (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3925	   (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3926	   (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3927	   ;; Emphasis
3928	   (if em
3929               (if (featurep 'xemacs)
3930                   '(org-do-emphasis-faces (0 nil append))
3931                 '(org-do-emphasis-faces)))
3932	   ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3933	   '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3934	     2 'bold prepend)
3935	   (if org-provide-checkbox-statistics
3936	       '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3937		 (0 (org-get-checkbox-statistics-face) t)))
3938	   ;; COMMENT
3939	   (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3940			 "\\|" org-quote-string "\\)\\>")
3941		 '(1 'org-special-keyword t))
3942	   '("^#.*" (0 'font-lock-comment-face t))
3943	   ;; DONE
3944	   (if org-fontify-done-headline
3945	       (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3946		     '(1 'org-done t) '(2 'org-headline-done t))
3947	     (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3948		   '(1 'org-done t)))
3949	   ;; Table stuff
3950	   '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3951	   '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3952	   '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3953	   (if org-format-transports-properties-p
3954	       '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3955	   '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
3956	   )))
3957    (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3958    ;; Now set the full font-lock-keywords
3959    (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3960    (org-set-local 'font-lock-defaults
3961		   '(org-font-lock-keywords t nil nil backward-paragraph))
3962    (kill-local-variable 'font-lock-keywords) nil))
3963
3964(defvar org-m nil)
3965(defvar org-l nil)
3966(defvar org-f nil)
3967(defun org-get-level-face (n)
3968  "Get the right face for match N in font-lock matching of healdines."
3969  (setq org-l (- (match-end 2) (match-beginning 1)))
3970  (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3971;  (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3972  (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3973  (cond
3974   ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3975   ((eq n 2) org-f)
3976   (t (if org-level-color-stars-only nil org-f))))
3977
3978(defun org-unfontify-region (beg end &optional maybe_loudly)
3979  "Remove fontification and activation overlays from links."
3980  (font-lock-default-unfontify-region beg end)
3981  (let* ((buffer-undo-list t)
3982	 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3983	 (inhibit-modification-hooks t)
3984	 deactivate-mark buffer-file-name buffer-file-truename)
3985    (remove-text-properties beg end
3986			    '(mouse-face t keymap t org-linked-text t
3987					 rear-nonsticky t
3988					 invisible t intangible t))))
3989
3990;;;; Visibility cycling, including org-goto and indirect buffer
3991
3992;;; Cycling
3993
3994(defvar org-cycle-global-status nil)
3995(make-variable-buffer-local 'org-cycle-global-status)
3996(defvar org-cycle-subtree-status nil)
3997(make-variable-buffer-local 'org-cycle-subtree-status)
3998
3999;;;###autoload
4000(defun org-cycle (&optional arg)
4001  "Visibility cycling for Org-mode.
4002
4003- When this function is called with a prefix argument, rotate the entire
4004  buffer through 3 states (global cycling)
4005  1. OVERVIEW: Show only top-level headlines.
4006  2. CONTENTS: Show all headlines of all levels, but no body text.
4007  3. SHOW ALL: Show everything.
4008
4009- When point is at the beginning of a headline, rotate the subtree started
4010  by this line through 3 different states (local cycling)
4011  1. FOLDED:   Only the main headline is shown.
4012  2. CHILDREN: The main headline and the direct children are shown.
4013               From this state, you can move to one of the children
4014               and zoom in further.
4015  3. SUBTREE:  Show the entire subtree, including body text.
4016
4017- When there is a numeric prefix, go up to a heading with level ARG, do
4018  a `show-subtree' and return to the previous cursor position.  If ARG
4019  is negative, go up that many levels.
4020
4021- When point is not at the beginning of a headline, execute
4022  `indent-relative', like TAB normally does.  See the option
4023  `org-cycle-emulate-tab' for details.
4024
4025- Special case: if point is the the beginning of the buffer and there is
4026  no headline in line 1, this function will act as if called with prefix arg."
4027  (interactive "P")
4028  (let* ((outline-regexp
4029	  (if (and (org-mode-p) org-cycle-include-plain-lists)
4030	      "\\(?:\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4031	    outline-regexp))
4032	 (bob-special (and org-cycle-global-at-bob (bobp)
4033			   (not (looking-at outline-regexp))))
4034	 (org-cycle-hook
4035	  (if bob-special
4036	      (delq 'org-optimize-window-after-visibility-change
4037		    (copy-sequence org-cycle-hook))
4038	    org-cycle-hook))
4039	 (pos (point)))
4040
4041    (if (or bob-special (equal arg '(4)))
4042	;; special case:  use global cycling
4043	(setq arg t))
4044
4045    (cond
4046
4047     ((org-at-table-p 'any)
4048      ;; Enter the table or move to the next field in the table
4049      (or (org-table-recognize-table.el)
4050	  (progn
4051	    (if arg (org-table-edit-field t)
4052	      (org-table-justify-field-maybe)
4053	      (call-interactively 'org-table-next-field)))))
4054
4055     ((eq arg t) ;; Global cycling
4056
4057      (cond
4058       ((and (eq last-command this-command)
4059	     (eq org-cycle-global-status 'overview))
4060	;; We just created the overview - now do table of contents
4061	;; This can be slow in very large buffers, so indicate action
4062	(message "CONTENTS...")
4063	(org-content)
4064	(message "CONTENTS...done")
4065	(setq org-cycle-global-status 'contents)
4066	(run-hook-with-args 'org-cycle-hook 'contents))
4067
4068       ((and (eq last-command this-command)
4069	     (eq org-cycle-global-status 'contents))
4070	;; We just showed the table of contents - now show everything
4071	(show-all)
4072	(message "SHOW ALL")
4073	(setq org-cycle-global-status 'all)
4074	(run-hook-with-args 'org-cycle-hook 'all))
4075
4076       (t
4077	;; Default action: go to overview
4078	(org-overview)
4079	(message "OVERVIEW")
4080	(setq org-cycle-global-status 'overview)
4081	(run-hook-with-args 'org-cycle-hook 'overview))))
4082
4083     ((integerp arg)
4084      ;; Show-subtree, ARG levels up from here.
4085      (save-excursion
4086	(org-back-to-heading)
4087	(outline-up-heading (if (< arg 0) (- arg)
4088			      (- (funcall outline-level) arg)))
4089	(org-show-subtree)))
4090
4091     ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4092      ;; At a heading: rotate between three different views
4093      (org-back-to-heading)
4094      (let ((goal-column 0) eoh eol eos)
4095	;; First, some boundaries
4096	(save-excursion
4097	  (org-back-to-heading)
4098	  (save-excursion
4099	    (beginning-of-line 2)
4100	    (while (and (not (eobp)) ;; this is like `next-line'
4101			(get-char-property (1- (point)) 'invisible))
4102	      (beginning-of-line 2)) (setq eol (point)))
4103	  (outline-end-of-heading)   (setq eoh (point))
4104	  (org-end-of-subtree t)
4105	  (skip-chars-forward " \t\n")
4106	  (beginning-of-line 1) ; in case this is an item
4107	  (setq eos (1- (point))))
4108	;; Find out what to do next and set `this-command'
4109	(cond
4110	 ((= eos eoh)
4111	  ;; Nothing is hidden behind this heading
4112	  (message "EMPTY ENTRY")
4113	  (setq org-cycle-subtree-status nil))
4114	 ((>= eol eos)
4115	  ;; Entire subtree is hidden in one line: open it
4116	  (org-show-entry)
4117	  (show-children)
4118	  (message "CHILDREN")
4119	  (setq org-cycle-subtree-status 'children)
4120	  (run-hook-with-args 'org-cycle-hook 'children))
4121	 ((and (eq last-command this-command)
4122	       (eq org-cycle-subtree-status 'children))
4123	  ;; We just showed the children, now show everything.
4124	  (org-show-subtree)
4125	  (message "SUBTREE")
4126	  (setq org-cycle-subtree-status 'subtree)
4127	  (run-hook-with-args 'org-cycle-hook 'subtree))
4128	 (t
4129	  ;; Default action: hide the subtree.
4130	  (hide-subtree)
4131	  (message "FOLDED")
4132	  (setq org-cycle-subtree-status 'folded)
4133	  (run-hook-with-args 'org-cycle-hook 'folded)))))
4134
4135     ;; TAB emulation
4136     (buffer-read-only (org-back-to-heading))
4137
4138     ((org-try-cdlatex-tab))
4139
4140     ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4141	       (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4142	       (or (and (eq org-cycle-emulate-tab 'white)
4143			(= (match-end 0) (point-at-eol)))
4144		   (and (eq org-cycle-emulate-tab 'whitestart)
4145			(>= (match-end 0) pos))))
4146	  t
4147	(eq org-cycle-emulate-tab t))
4148      (if (and (looking-at "[ \n\r\t]")
4149	       (string-match "^[ \t]*$" (buffer-substring
4150					 (point-at-bol) (point))))
4151	  (progn
4152	    (beginning-of-line 1)
4153	    (and (looking-at "[ \t]+") (replace-match ""))))
4154      (indent-relative))
4155
4156     (t (save-excursion
4157	  (org-back-to-heading)
4158	  (org-cycle))))))
4159
4160;;;###autoload
4161(defun org-global-cycle (&optional arg)
4162  "Cycle the global visibility.  For details see `org-cycle'."
4163  (interactive "P")
4164  (let ((org-cycle-include-plain-lists
4165	 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4166    (if (integerp arg)
4167	(progn
4168	  (show-all)
4169	  (hide-sublevels arg)
4170	  (setq org-cycle-global-status 'contents))
4171      (org-cycle '(4)))))
4172
4173(defun org-overview ()
4174  "Switch to overview mode, shoing only top-level headlines.
4175Really, this shows all headlines with level equal or greater than the level
4176of the first headline in the buffer.  This is important, because if the
4177first headline is not level one, then (hide-sublevels 1) gives confusing
4178results."
4179  (interactive)
4180  (hide-sublevels (save-excursion
4181		    (goto-char (point-min))
4182		    (if (re-search-forward (concat "^" outline-regexp) nil t)
4183			(progn
4184			  (goto-char (match-beginning 0))
4185			  (funcall outline-level))
4186		      1))))
4187
4188(defun org-content (&optional arg)
4189  "Show all headlines in the buffer, like a table of contents.
4190With numerical argument N, show content up to level N."
4191  (interactive "P")
4192  (save-excursion
4193    ;; Visit all headings and show their offspring
4194    (and (integerp arg) (org-overview))
4195    (goto-char (point-max))
4196    (catch 'exit
4197      (while (and (progn (condition-case nil
4198			     (outline-previous-visible-heading 1)
4199			   (error (goto-char (point-min))))
4200			 t)
4201		  (looking-at outline-regexp))
4202	(if (integerp arg)
4203	    (show-children (1- arg))
4204	  (show-branches))
4205	(if (bobp) (throw 'exit nil))))))
4206
4207
4208(defun org-optimize-window-after-visibility-change (state)
4209  "Adjust the window after a change in outline visibility.
4210This function is the default value of the hook `org-cycle-hook'."
4211  (when (get-buffer-window (current-buffer))
4212    (cond
4213     ((eq state 'overview) (org-first-headline-recenter 1))
4214     ((eq state 'content)  nil)
4215     ((eq state 'all)      nil)
4216     ((eq state 'folded)   nil)
4217     ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4218     ((eq state 'subtree)  (or (org-subtree-end-visible-p) (recenter 1))))))
4219
4220(defun org-subtree-end-visible-p ()
4221  "Is the end of the current subtree visible?"
4222  (pos-visible-in-window-p
4223   (save-excursion (org-end-of-subtree t) (point))))
4224
4225(defun org-first-headline-recenter (&optional N)
4226  "Move cursor to the first headline and recenter the headline.
4227Optional argument N means, put the headline into the Nth line of the window."
4228  (goto-char (point-min))
4229  (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4230    (beginning-of-line)
4231    (recenter (prefix-numeric-value N))))
4232
4233;;; Org-goto
4234
4235(defvar org-goto-window-configuration nil)
4236(defvar org-goto-marker nil)
4237(defvar org-goto-map (make-sparse-keymap))
4238(let ((cmds '(isearch-forward isearch-backward)) cmd)
4239  (while (setq cmd (pop cmds))
4240    (substitute-key-definition cmd cmd org-goto-map global-map)))
4241(define-key org-goto-map "\C-m"     'org-goto-ret)
4242(define-key org-goto-map [(left)]   'org-goto-left)
4243(define-key org-goto-map [(right)]  'org-goto-right)
4244(define-key org-goto-map [(?q)]     'org-goto-quit)
4245(define-key org-goto-map [(control ?g)] 'org-goto-quit)
4246(define-key org-goto-map "\C-i" 'org-cycle)
4247(define-key org-goto-map [(tab)] 'org-cycle)
4248(define-key org-goto-map [(down)] 'outline-next-visible-heading)
4249(define-key org-goto-map [(up)] 'outline-previous-visible-heading)
4250(define-key org-goto-map "n" 'outline-next-visible-heading)
4251(define-key org-goto-map "p" 'outline-previous-visible-heading)
4252(define-key org-goto-map "f" 'outline-forward-same-level)
4253(define-key org-goto-map "b" 'outline-backward-same-level)
4254(define-key org-goto-map "u" 'outline-up-heading)
4255(define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
4256(define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
4257(define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
4258(define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
4259(define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
4260(let ((l '(1 2 3 4 5 6 7 8 9 0)))
4261  (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
4262
4263(defconst org-goto-help
4264"Select a location to jump to, press RET
4265\[Up]/[Down]=next/prev headline   TAB=cycle visibility   RET=select   [Q]uit")
4266
4267(defun org-goto ()
4268  "Go to a different location of the document, keeping current visibility.
4269
4270When you want to go to a different location in a document, the fastest way
4271is often to fold the entire buffer and then dive into the tree.  This
4272method has the disadvantage, that the previous location will be folded,
4273which may not be what you want.
4274
4275This command works around this by showing a copy of the current buffer in
4276overview mode.  You can dive into the tree in that copy, to find the
4277location you want to reach.  When pressing RET, the command returns to the
4278original buffer in which the visibility is still unchanged.  It then jumps
4279to the new location, making it and the headline hierarchy above it visible."
4280  (interactive)
4281  (let* ((org-goto-start-pos (point))
4282	 (selected-point
4283	  (org-get-location (current-buffer) org-goto-help)))
4284    (if selected-point
4285	(progn
4286	  (org-mark-ring-push org-goto-start-pos)
4287	  (goto-char selected-point)
4288	  (if (or (org-invisible-p) (org-invisible-p2))
4289	      (org-show-context 'org-goto)))
4290      (error "Quit"))))
4291
4292(defvar org-selected-point nil) ; dynamically scoped parameter
4293
4294(defun org-get-location (buf help)
4295  "Let the user select a location in the Org-mode buffer BUF.
4296This function uses a recursive edit.  It returns the selected position
4297or nil."
4298  (let (org-selected-point)
4299    (save-excursion
4300      (save-window-excursion
4301	(delete-other-windows)
4302	(switch-to-buffer (get-buffer-create "*org-goto*"))
4303	(with-output-to-temp-buffer "*Help*"
4304	  (princ help))
4305	(shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4306	(setq buffer-read-only nil)
4307	(erase-buffer)
4308	(insert-buffer-substring buf)
4309	(let ((org-startup-truncated t)
4310	      (org-startup-folded t)
4311	      (org-startup-align-all-tables nil))
4312	  (org-mode))
4313	(setq buffer-read-only t)
4314	(if (and (boundp 'org-goto-start-pos)
4315		 (integer-or-marker-p org-goto-start-pos))
4316	    (let ((org-show-hierarchy-above t)
4317		  (org-show-siblings t)
4318		  (org-show-following-heading t))
4319	      (goto-char org-goto-start-pos)
4320	      (and (org-invisible-p) (org-show-context)))
4321	  (goto-char (point-min)))
4322	(org-beginning-of-line)
4323	(message "Select location and press RET")
4324	;; now we make sure that during selection, ony very few keys work
4325	;; and that it is impossible to switch to another window.
4326	(let ((gm (current-global-map))
4327	      (overriding-local-map org-goto-map))
4328	  (unwind-protect
4329	      (progn
4330		(use-global-map org-goto-map)
4331		(recursive-edit))
4332	    (use-global-map gm)))))
4333    (kill-buffer "*org-goto*")
4334    org-selected-point))
4335
4336(defun org-goto-ret (&optional arg)
4337  "Finish `org-goto' by going to the new location."
4338  (interactive "P")
4339  (setq org-selected-point (point)
4340	current-prefix-arg arg)
4341  (throw 'exit nil))
4342
4343(defun org-goto-left ()
4344  "Finish `org-goto' by going to the new location."
4345  (interactive)
4346  (if (org-on-heading-p)
4347      (progn
4348	(beginning-of-line 1)
4349	(setq org-selected-point (point)
4350	      current-prefix-arg (- (match-end 0) (match-beginning 0)))
4351	(throw 'exit nil))
4352    (error "Not on a heading")))
4353
4354(defun org-goto-right ()
4355  "Finish `org-goto' by going to the new location."
4356  (interactive)
4357  (if (org-on-heading-p)
4358      (progn
4359	(outline-end-of-subtree)
4360	(or (eobp) (forward-char 1))
4361	(setq org-selected-point (point)
4362	      current-prefix-arg (- (match-end 0) (match-beginning 0)))
4363	(throw 'exit nil))
4364    (error "Not on a heading")))
4365
4366(defun org-goto-quit ()
4367  "Finish `org-goto' without cursor motion."
4368  (interactive)
4369  (setq org-selected-point nil)
4370  (throw 'exit nil))
4371
4372;;; Indirect buffer display of subtrees
4373
4374(defvar org-indirect-dedicated-frame nil
4375  "This is the frame being used for indirect tree display.")
4376(defvar org-last-indirect-buffer nil)
4377
4378(defun org-tree-to-indirect-buffer (&optional arg)
4379  "Create indirect buffer and narrow it to current subtree.
4380With numerical prefix ARG, go up to this level and then take that tree.
4381If ARG is negative, go up that many levels.
4382Normally this command removes the indirect buffer previously made
4383with this command.  However, when called with a C-u prefix, the last buffer
4384is kept so that you can work with several indirect buffers at the same time.
4385If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4386requests that a new frame be made for the new buffer, so that the dedicated
4387frame is not changed."
4388  (interactive "P")
4389  (let ((cbuf (current-buffer))
4390	(cwin (selected-window))
4391	(pos (point))
4392	beg end level heading ibuf)
4393    (save-excursion
4394      (org-back-to-heading t)
4395      (when (numberp arg)
4396	(setq level (org-outline-level))
4397	(if (< arg 0) (setq arg (+ level arg)))
4398	(while (> (setq level (org-outline-level)) arg)
4399	  (outline-up-heading 1 t)))
4400      (setq beg (point)
4401	    heading (org-get-heading))
4402      (org-end-of-subtree t) (setq end (point)))
4403    (if (and (not arg)
4404	     (buffer-live-p org-last-indirect-buffer))
4405	(kill-buffer org-last-indirect-buffer))
4406    (setq ibuf (org-get-indirect-buffer cbuf)
4407	  org-last-indirect-buffer ibuf)
4408    (cond
4409     ((or (eq org-indirect-buffer-display 'new-frame)
4410	  (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4411      (select-frame (make-frame))
4412      (delete-other-windows)
4413      (switch-to-buffer ibuf)
4414      (org-set-frame-title heading))
4415     ((eq org-indirect-buffer-display 'dedicated-frame)
4416      (raise-frame
4417       (select-frame (or (and org-indirect-dedicated-frame
4418			      (frame-live-p org-indirect-dedicated-frame)
4419			      org-indirect-dedicated-frame)
4420			 (setq org-indirect-dedicated-frame (make-frame)))))
4421      (delete-other-windows)
4422      (switch-to-buffer ibuf)
4423      (org-set-frame-title (concat "Indirect: " heading)))
4424     ((eq org-indirect-buffer-display 'current-window)
4425      (switch-to-buffer ibuf))
4426     ((eq org-indirect-buffer-display 'other-window)
4427      (pop-to-buffer ibuf))
4428     (t (error "Invalid value.")))
4429    (if (featurep 'xemacs)
4430        (save-excursion (org-mode) (turn-on-font-lock)))
4431    (narrow-to-region beg end)
4432    (show-all)
4433    (goto-char pos)
4434    (and (window-live-p cwin) (select-window cwin))))
4435
4436(defun org-get-indirect-buffer (&optional buffer)
4437  (setq buffer (or buffer (current-buffer)))
4438  (let ((n 1) (base (buffer-name buffer)) bname)
4439    (while (buffer-live-p
4440	    (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4441      (setq n (1+ n)))
4442    (condition-case nil
4443        (make-indirect-buffer buffer bname 'clone)
4444      (error (make-indirect-buffer buffer bname)))))
4445
4446(defun org-set-frame-title (title)
4447  "Set the title of the current frame to the string TITLE."
4448  ;; FIXME: how to name a single frame in XEmacs???
4449  (unless (featurep 'xemacs)
4450    (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4451
4452;;;; Structure editing
4453
4454;;; Inserting headlines
4455
4456(defun org-insert-heading (&optional force-heading)
4457  "Insert a new heading or item with same depth at point.
4458If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4459If point is at the beginning of a headline, insert a sibling before the
4460current headline.  If point is in the middle of a headline, split the headline
4461at that position and make the rest of the headline part of the sibling below
4462the current headline."
4463  (interactive "P")
4464  (if (= (buffer-size) 0)
4465      (insert "\n* ")
4466    (when (or force-heading (not (org-insert-item)))
4467      (let* ((head (save-excursion
4468		     (condition-case nil
4469			 (progn
4470			   (org-back-to-heading)
4471			   (match-string 0))
4472		       (error "*"))))
4473	     (blank (cdr (assq 'heading org-blank-before-new-entry)))
4474	     pos)
4475	(cond
4476	 ((and (org-on-heading-p) (bolp)
4477	       (save-excursion (backward-char 1) (not (org-invisible-p))))
4478	  (open-line (if blank 2 1)))
4479	 ((and (bolp) (save-excursion
4480			(backward-char 1) (not (org-invisible-p))))
4481	  nil)
4482	 (t (newline (if blank 2 1))))
4483	(insert head) (just-one-space)
4484	(setq pos (point))
4485	(end-of-line 1)
4486	(unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4487	(run-hooks 'org-insert-heading-hook)))))
4488
4489
4490(defun org-insert-todo-heading (arg)
4491  "Insert a new heading with the same level and TODO state as current heading.
4492If the heading has no TODO state, or if the state is DONE, use the first
4493state (TODO by default).  Also with prefix arg, force first state."
4494  (interactive "P")
4495  (when (not (org-insert-item 'checkbox))
4496    (org-insert-heading)
4497    (save-excursion
4498      (org-back-to-heading)
4499      (outline-previous-heading)
4500      (looking-at org-todo-line-regexp))
4501    (if (or arg
4502	    (not (match-beginning 2))
4503	    (equal (match-string 2) org-done-string))
4504	(insert (car org-todo-keywords) " ")
4505      (insert (match-string 2) " "))))
4506
4507;;; Promotion and Demotion
4508
4509(defun org-promote-subtree ()
4510  "Promote the entire subtree.
4511See also `org-promote'."
4512  (interactive)
4513  (save-excursion
4514    (org-map-tree 'org-promote))
4515  (org-fix-position-after-promote))
4516
4517(defun org-demote-subtree ()
4518  "Demote the entire subtree.  See `org-demote'.
4519See also `org-promote'."
4520  (interactive)
4521  (save-excursion
4522    (org-map-tree 'org-demote))
4523  (org-fix-position-after-promote))
4524
4525
4526(defun org-do-promote ()
4527  "Promote the current heading higher up the tree.
4528If the region is active in `transient-mark-mode', promote all headings
4529in the region."
4530  (interactive)
4531  (save-excursion
4532    (if (org-region-active-p)
4533	(org-map-region 'org-promote (region-beginning) (region-end))
4534      (org-promote)))
4535  (org-fix-position-after-promote))
4536
4537(defun org-do-demote ()
4538  "Demote the current heading lower down the tree.
4539If the region is active in `transient-mark-mode', demote all headings
4540in the region."
4541  (interactive)
4542  (save-excursion
4543    (if (org-region-active-p)
4544	(org-map-region 'org-demote (region-beginning) (region-end))
4545      (org-demote)))
4546  (org-fix-position-after-promote))
4547
4548(defun org-fix-position-after-promote ()
4549  "Make sure that after pro/demotion cursor position is right."
4550  (let ((pos (point)))
4551    (when (save-excursion
4552	    (beginning-of-line 1)
4553	    (looking-at org-todo-line-regexp)
4554	    (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4555      (cond ((eobp) (insert " "))
4556	    ((eolp) (insert " "))
4557	    ((equal (char-after) ?\ ) (forward-char 1))))))
4558
4559(defun org-get-legal-level (level &optional change)
4560  "Rectify a level change under the influence of `org-odd-levels-only'
4561LEVEL is a current level, CHANGE is by how much the level should be
4562modified.  Even if CHANGE is nil, LEVEL may be returned modified because
4563even level numbers will become the next higher odd number."
4564  (if org-odd-levels-only
4565      (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4566	    ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4567	    ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4568    (max 1 (+ level change))))
4569
4570(defun org-promote ()
4571  "Promote the current heading higher up the tree.
4572If the region is active in `transient-mark-mode', promote all headings
4573in the region."
4574  (org-back-to-heading t)
4575  (let* ((level (save-match-data (funcall outline-level)))
4576	 (up-head (make-string (org-get-legal-level level -1) ?*))
4577	 (diff (abs (- level (length up-head)))))
4578    (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4579    (replace-match up-head nil t)
4580    ;; Fixup tag positioning
4581    (and org-auto-align-tags (org-set-tags nil t))
4582    (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4583
4584(defun org-demote ()
4585  "Demote the current heading lower down the tree.
4586If the region is active in `transient-mark-mode', demote all headings
4587in the region."
4588  (org-back-to-heading t)
4589  (let* ((level (save-match-data (funcall outline-level)))
4590	 (down-head (make-string (org-get-legal-level level 1) ?*))
4591	 (diff (abs (- level (length down-head)))))
4592    (replace-match down-head nil t)
4593    ;; Fixup tag positioning
4594    (and org-auto-align-tags (org-set-tags nil t))
4595    (if org-adapt-indentation (org-fixup-indentation diff))))
4596
4597(defun org-map-tree (fun)
4598  "Call FUN for every heading underneath the current one."
4599  (org-back-to-heading)
4600  (let ((level (funcall outline-level)))
4601    (save-excursion
4602      (funcall fun)
4603      (while (and (progn
4604		    (outline-next-heading)
4605		    (> (funcall outline-level) level))
4606		  (not (eobp)))
4607	(funcall fun)))))
4608
4609(defun org-map-region (fun beg end)
4610  "Call FUN for every heading between BEG and END."
4611  (let ((org-ignore-region t))
4612    (save-excursion
4613      (setq end (copy-marker end))
4614      (goto-char beg)
4615      (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4616	       (< (point) end))
4617	  (funcall fun))
4618      (while (and (progn
4619		    (outline-next-heading)
4620		    (< (point) end))
4621		  (not (eobp)))
4622	(funcall fun)))))
4623
4624(defun org-fixup-indentation (diff)
4625  "Change the indentation in the current entry by DIFF
4626However, if any line in the current entry has no indentation, or if it
4627would end up with no indentation after the change, nothing at all is done."
4628  (save-excursion
4629    (let ((end (save-excursion (outline-next-heading)
4630			       (point-marker)))
4631	  (prohibit (if (> diff 0)
4632			"^\\S-"
4633		      (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4634	  col)
4635      (unless (save-excursion (re-search-forward prohibit end t))
4636	(while (re-search-forward "^[ \t]+" end t)
4637	  (goto-char (match-end 0))
4638	  (setq col (current-column))
4639	  (if (< diff 0) (replace-match ""))
4640	  (indent-to (+ diff col))))
4641      (move-marker end nil))))
4642
4643(defun org-convert-to-odd-levels ()
4644  "Convert an org-mode file with all levels allowed to one with odd levels.
4645This will leave level 1 alone, convert level 2 to level 3, level 3 to
4646level 5 etc."
4647  (interactive)
4648  (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4649    (let ((org-odd-levels-only nil) n)
4650      (save-excursion
4651	(goto-char (point-min))
4652	(while (re-search-forward "^\\*\\*+" nil t)
4653	  (setq n (1- (length (match-string 0))))
4654	  (while (>= (setq n (1- n)) 0)
4655	    (org-demote))
4656	  (end-of-line 1))))))
4657
4658
4659(defun org-convert-to-oddeven-levels ()
4660  "Convert an org-mode file with only odd levels to one with odd and even levels.
4661This promotes level 3 to level 2, level 5 to level 3 etc.  If the file contains a
4662section with an even level, conversion would destroy the structure of the file.  An error
4663is signaled in this case."
4664  (interactive)
4665  (goto-char (point-min))
4666  ;; First check if there are no even levels
4667  (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
4668    (org-show-context t)
4669    (error "Not all levels are odd in this file.  Conversion not possible."))
4670  (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4671    (let ((org-odd-levels-only nil) n)
4672      (save-excursion
4673	(goto-char (point-min))
4674	(while (re-search-forward "^\\*\\*+" nil t)
4675	  (setq n (/ (length (match-string 0)) 2))
4676	  (while (>= (setq n (1- n)) 0)
4677	    (org-promote))
4678	  (end-of-line 1))))))
4679
4680(defun org-tr-level (n)
4681  "Make N odd if required."
4682  (if org-odd-levels-only (1+ (/ n 2)) n))
4683
4684;;; Vertical tree motion, cutting and pasting of subtrees
4685
4686(defun org-move-subtree-up (&optional arg)
4687  "Move the current subtree up past ARG headlines of the same level."
4688  (interactive "p")
4689  (org-move-subtree-down (- (prefix-numeric-value arg))))
4690
4691(defun org-move-subtree-down (&optional arg)
4692  "Move the current subtree down past ARG headlines of the same level."
4693  (interactive "p")
4694  (setq arg (prefix-numeric-value arg))
4695  (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4696		   'outline-get-last-sibling))
4697	(ins-point (make-marker))
4698	(cnt (abs arg))
4699	beg end txt folded)
4700    ;; Select the tree
4701    (org-back-to-heading)
4702    (setq beg (point))
4703    (save-match-data
4704      (save-excursion (outline-end-of-heading)
4705		      (setq folded (org-invisible-p)))
4706      (outline-end-of-subtree))
4707    (outline-next-heading)
4708    (setq end (point))
4709    ;; Find insertion point, with error handling
4710    (goto-char beg)
4711    (while (> cnt 0)
4712      (or (and (funcall movfunc) (looking-at outline-regexp))
4713	  (progn (goto-char beg)
4714		 (error "Cannot move past superior level or buffer limit")))
4715      (setq cnt (1- cnt)))
4716    (if (> arg 0)
4717	;; Moving forward - still need to move over subtree
4718	(progn (outline-end-of-subtree)
4719	       (outline-next-heading)
4720	       (if (not (or (looking-at (concat "^" outline-regexp))
4721			    (bolp)))
4722		   (newline))))
4723    (move-marker ins-point (point))
4724    (setq txt (buffer-substring beg end))
4725    (delete-region beg end)
4726    (insert txt)
4727    (goto-char ins-point)
4728    (if folded (hide-subtree))
4729    (move-marker ins-point nil)))
4730
4731(defvar org-subtree-clip ""
4732  "Clipboard for cut and paste of subtrees.
4733This is actually only a copy of the kill, because we use the normal kill
4734ring.  We need it to check if the kill was created by `org-copy-subtree'.")
4735
4736(defvar org-subtree-clip-folded nil
4737  "Was the last copied subtree folded?
4738This is used to fold the tree back after pasting.")
4739
4740(defun org-cut-subtree ()
4741  "Cut the current subtree into the clipboard.
4742This is a short-hand for marking the subtree and then cutting it."
4743  (interactive)
4744  (org-copy-subtree 'cut))
4745
4746(defun org-copy-subtree (&optional cut)
4747  "Cut the current subtree into the clipboard.
4748This is a short-hand for marking the subtree and then copying it.
4749If CUT is non-nil, actually cut the subtree."
4750  (interactive)
4751  (let (beg end folded)
4752    (org-back-to-heading)
4753    (setq beg (point))
4754    (save-match-data
4755      (save-excursion (outline-end-of-heading)
4756		      (setq folded (org-invisible-p)))
4757      (outline-end-of-subtree))
4758    (if (equal (char-after) ?\n) (forward-char 1))
4759    (setq end (point))
4760    (goto-char beg)
4761    (when (> end beg)
4762      (setq org-subtree-clip-folded folded)
4763      (if cut (kill-region beg end) (copy-region-as-kill beg end))
4764      (setq org-subtree-clip (current-kill 0))
4765      (message "%s: Subtree with %d characters"
4766	       (if cut "Cut" "Copied")
4767	       (length org-subtree-clip)))))
4768
4769(defun org-paste-subtree (&optional level tree)
4770  "Paste the clipboard as a subtree, with modification of headline level.
4771The entire subtree is promoted or demoted in order to match a new headline
4772level.  By default, the new level is derived from the visible headings
4773before and after the insertion point, and taken to be the inferior headline
4774level of the two.  So if the previous visible heading is level 3 and the
4775next is level 4 (or vice versa), level 4 will be used for insertion.
4776This makes sure that the subtree remains an independent subtree and does
4777not swallow low level entries.
4778
4779You can also force a different level, either by using a numeric prefix
4780argument, or by inserting the heading marker by hand.  For example, if the
4781cursor is after \"*****\", then the tree will be shifted to level 5.
4782
4783If you want to insert the tree as is, just use \\[yank].
4784
4785If optional TREE is given, use this text instead of the kill ring."
4786  (interactive "P")
4787  (unless (org-kill-is-subtree-p tree)
4788    (error
4789     (substitute-command-keys
4790      "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4791  (let* ((txt (or tree (and kill-ring (current-kill 0))))
4792	 (^re (concat "^\\(" outline-regexp "\\)"))
4793	 (re  (concat "\\(" outline-regexp "\\)"))
4794	 (^re_ (concat "\\(" outline-regexp "\\)[  \t]*"))
4795
4796	 (old-level (if (string-match ^re txt)
4797			(- (match-end 0) (match-beginning 0))
4798		      -1))
4799	 (force-level (cond (level (prefix-numeric-value level))
4800			    ((string-match
4801			      ^re_ (buffer-substring (point-at-bol) (point)))
4802			     (- (match-end 0) (match-beginning 0)))
4803			    (t nil)))
4804	 (previous-level (save-excursion
4805			   (condition-case nil
4806			       (progn
4807				 (outline-previous-visible-heading 1)
4808				 (if (looking-at re)
4809				     (- (match-end 0) (match-beginning 0))
4810				   1))
4811			     (error 1))))
4812	 (next-level (save-excursion
4813		       (condition-case nil
4814			   (progn
4815			     (outline-next-visible-heading 1)
4816			     (if (looking-at re)
4817				 (- (match-end 0) (match-beginning 0))
4818			       1))
4819			 (error 1))))
4820	 (new-level (or force-level (max previous-level next-level)))
4821	 (shift (if (or (= old-level -1)
4822			(= new-level -1)
4823			(= old-level new-level))
4824		    0
4825		  (- new-level old-level)))
4826	 (shift1 shift)
4827	 (delta (if (> shift 0) -1 1))
4828	 (func (if (> shift 0) 'org-demote 'org-promote))
4829	 (org-odd-levels-only nil)
4830	 beg end)
4831    ;; Remove the forces level indicator
4832    (if force-level
4833	(delete-region (point-at-bol) (point)))
4834    ;; Make sure we start at the beginning of an empty line
4835    (if (not (bolp)) (insert "\n"))
4836    (if (not (looking-at "[ \t]*$"))
4837	(progn (insert "\n") (backward-char 1)))
4838    ;; Paste
4839    (setq beg (point))
4840    (if (string-match "[ \t\r\n]+\\'" txt)
4841	(setq txt (replace-match "\n" t t txt)))
4842    (insert txt)
4843    (setq end (point))
4844    (if (looking-at "[ \t\r\n]+")
4845	(replace-match "\n"))
4846    (goto-char beg)
4847    ;; Shift if necessary
4848    (if (= shift 0)
4849	(message "Pasted at level %d, without shift" new-level)
4850      (save-restriction
4851	(narrow-to-region beg end)
4852	(while (not (= shift 0))
4853	  (org-map-region func (point-min) (point-max))
4854	  (setq shift (+ delta shift)))
4855	(goto-char (point-min))
4856	(message "Pasted at level %d, with shift by %d levels"
4857		 new-level shift1)))
4858    (if (and kill-ring
4859	     (eq org-subtree-clip (current-kill 0))
4860	     org-subtree-clip-folded)
4861	;; The tree was folded before it was killed/copied
4862	(hide-subtree))))
4863
4864(defun org-kill-is-subtree-p (&optional txt)
4865  "Check if the current kill is an outline subtree, or a set of trees.
4866Returns nil if kill does not start with a headline, or if the first
4867headline level is not the largest headline level in the tree.
4868So this will actually accept several entries of equal levels as well,
4869which is OK for `org-paste-subtree'.
4870If optional TXT is given, check this string instead of the current kill."
4871  (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4872	 (start-level (and kill
4873			   (string-match (concat "\\`" outline-regexp) kill)
4874			   (- (match-end 0) (match-beginning 0))))
4875	 (re (concat "^" outline-regexp))
4876	 (start 1))
4877    (if (not start-level)
4878	nil  ;; does not even start with a heading
4879      (catch 'exit
4880	(while (setq start (string-match re kill (1+ start)))
4881	  (if (< (- (match-end 0) (match-beginning 0)) start-level)
4882	      (throw 'exit nil)))
4883	t))))
4884
4885(defun org-narrow-to-subtree ()
4886  "Narrow buffer to the current subtree."
4887  (interactive)
4888  (save-excursion
4889    (narrow-to-region
4890     (progn (org-back-to-heading) (point))
4891     (progn (org-end-of-subtree t) (point)))))
4892
4893
4894;;; Outline Sorting
4895
4896(defun org-sort (with-case)
4897  "Call `org-sort-entries' or `org-table-sort-lines', depending on context."
4898  (interactive "P")
4899  (if (org-at-table-p)
4900      (org-call-with-arg 'org-table-sort-lines with-case)
4901    (org-call-with-arg 'org-sort-entries with-case)))
4902
4903(defun org-sort-entries (&optional with-case sorting-type)
4904  "Sort entries on a certain level of an outline tree.
4905If there is an active region, the entries in the region are sorted.
4906Else, if the cursor is before the first entry, sort the top-level items.
4907Else, the children of the entry at point are sorted.
4908
4909Sorting can be alphabetically, numerically, and by date/time as given by
4910the first time stamp in the entry.  The command prompts for the sorting
4911type unless it has been given to the function through the SORTING-TYPE
4912argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T).
4913
4914Comparing entries ignores case by default.  However, with an optional argument
4915WITH-CASE, the sorting considers case as well.  With two prefix arguments
4916`C-u C-u', sorting is case-sensitive and duplicate entries will be removed."
4917  (interactive "P")
4918  (let ((unique (equal with-case '(16)))
4919	start beg end entries stars re re2 p nentries (nremoved 0)
4920	last txt what)
4921    ;; Find beginning and end of region to sort
4922    (cond
4923     ((org-region-active-p)
4924      ;; we will sort the region
4925      (setq end (region-end)
4926	    what "region")
4927      (goto-char (region-beginning))
4928      (if (not (org-on-heading-p)) (outline-next-heading))
4929      (setq start (point)))
4930     ((or (org-on-heading-p)
4931	  (condition-case nil (progn (org-back-to-heading) t) (error nil)))
4932      ;; we will sort the children of the current headline
4933      (org-back-to-heading)
4934      (setq start (point) end (org-end-of-subtree) what "children")
4935      (goto-char start)
4936      (show-subtree)
4937      (outline-next-heading))
4938     (t
4939      ;; we will sort the top-level entries in this file
4940      (goto-char (point-min))
4941      (or (org-on-heading-p) (outline-next-heading))
4942      (setq start (point) end (point-max) what "top-level")
4943      (goto-char start)
4944      (show-all)))
4945    (setq beg (point))
4946    (if (>= (point) end) (error "Nothing to sort"))
4947    (looking-at "\\(\\*+\\)")
4948    (setq stars (match-string 1)
4949	  re (concat "^" (regexp-quote stars) " +")
4950	  re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
4951	  txt (buffer-substring beg end))
4952    (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
4953    (if (and (not (equal stars "*")) (string-match re2 txt))
4954	(error "Region to sort contains a level above the first entry"))
4955    ;; Make a list that can be sorted.
4956    ;; The car is the string for comparison, the cdr is the subtree
4957    (message "Sorting entries...")
4958    (setq entries
4959	  (mapcar
4960	   (lambda (x)
4961	     (string-match "^.*\\(\n.*\\)?" x) ; take two lines
4962	     (cons (match-string 0 x) x))
4963	   (org-split-string txt re)))
4964
4965    ;; Sort the list
4966    (save-excursion
4967      (goto-char start)
4968      (setq entries (org-do-sort entries what with-case sorting-type)))
4969
4970    ;; Delete the old stuff
4971    (goto-char beg)
4972    (kill-region beg end)
4973    (setq nentries (length entries))
4974    ;; Insert the sorted entries, and remove duplicates if this is required
4975    (while (setq p (pop entries))
4976      (if (and unique (equal last (setq last (org-trim (cdr p)))))
4977	  (setq nremoved (1+ nremoved)) ; same entry as before, skip it
4978	(insert stars " " (cdr p))))
4979    (goto-char start)
4980    (message "Sorting entries...done (%d entries%s)"
4981	     nentries
4982	     (if unique (format ", %d duplicates removed" nremoved) ""))))
4983
4984(defun org-do-sort (table what &optional with-case sorting-type)
4985  "Sort TABLE of WHAT according to SORTING-TYPE.
4986The user will be prompted for the SORTING-TYPE if the call to this
4987function does not specify it.  WHAT is only for the prompt, to indicate
4988what is being sorted.  The sorting key will be extracted from
4989the car of the elements of the table.
4990If WITH-CASE is non-nil, the sorting will be case-sensitive."
4991  (unless sorting-type
4992    (message
4993     "Sort %s: [a]lphabetically [n]umerically [t]ime. A/N/T means reversed:"
4994     what)
4995    (setq sorting-type (read-char-exclusive)))
4996  (let ((dcst (downcase sorting-type))
4997	extractfun comparefun)
4998    ;; Define the appropriate functions
4999    (cond
5000     ((= dcst ?n)
5001      (setq extractfun 'string-to-number
5002	    comparefun (if (= dcst sorting-type) '< '>)))
5003     ((= dcst ?a)
5004      (setq extractfun (if with-case 'identity 'downcase)
5005	    comparefun (if (= dcst sorting-type)
5006			   'string<
5007			 (lambda (a b) (and (not (string< a b))
5008					    (not (string= a b)))))))
5009     ((= dcst ?t)
5010      (setq extractfun
5011	    (lambda (x)
5012	      (if (string-match org-ts-regexp x)
5013		  (time-to-seconds
5014		   (org-time-string-to-time (match-string 0 x)))
5015		0))
5016	    comparefun (if (= dcst sorting-type) '< '>)))
5017     (t (error "Invalid sorting type `%c'" sorting-type)))
5018
5019    (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5020		  table)
5021	  (lambda (a b) (funcall comparefun (car a) (car b))))))
5022
5023;;;; Plain list items, including checkboxes
5024
5025;;; Plain list items
5026
5027(defun org-at-item-p ()
5028  "Is point in a line starting a hand-formatted item?"
5029  (let ((llt org-plain-list-ordered-item-terminator))
5030    (save-excursion
5031      (goto-char (point-at-bol))
5032      (looking-at
5033       (cond
5034	((eq llt t)  "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5035	((= llt ?.)  "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5036	((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5037	(t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5038
5039
5040(defun org-in-item-p ()
5041  "It the cursor inside a plain list item.
5042Does not have to be the first line."
5043  (save-excursion
5044    (condition-case nil
5045	(progn
5046	  (org-beginning-of-item)
5047	  (org-at-item-p)
5048	  t)
5049      (error nil))))
5050
5051(defun org-insert-item (&optional checkbox)
5052  "Insert a new item at the current level.
5053Return t when things worked, nil when we are not in an item."
5054  (when (save-excursion
5055	  (condition-case nil
5056	      (progn
5057		(org-beginning-of-item)
5058		(org-at-item-p)
5059		(if (org-invisible-p) (error "Invisible item"))
5060		t)
5061	    (error nil)))
5062    (let* ((bul (match-string 0))
5063	   (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5064				(match-end 0)))
5065	   (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5066	   pos)
5067      (cond
5068       ((and (org-at-item-p) (<= (point) eow))
5069	;; before the bullet
5070	(beginning-of-line 1)
5071	(open-line (if blank 2 1)))
5072       ((<= (point) eow)
5073	(beginning-of-line 1))
5074       (t (newline (if blank 2 1))))
5075      (insert bul (if checkbox "[ ]" ""))
5076      (just-one-space)
5077      (setq pos (point))
5078      (end-of-line 1)
5079      (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5080    (org-maybe-renumber-ordered-list)
5081    (and checkbox (org-update-checkbox-count-maybe))
5082    t))
5083
5084;;; Checkboxes
5085
5086(defun org-at-item-checkbox-p ()
5087  "Is point at a line starting a plain-list item with a checklet?"
5088  (and (org-at-item-p)
5089       (save-excursion
5090	 (goto-char (match-end 0))
5091	 (skip-chars-forward " \t")
5092	 (looking-at "\\[[ X]\\]"))))
5093
5094(defun org-toggle-checkbox (&optional arg)
5095  "Toggle the checkbox in the current line."
5096  (interactive "P")
5097  (catch 'exit
5098    (let (beg end status (firstnew 'unknown))
5099      (cond
5100       ((org-region-active-p)
5101	(setq beg (region-beginning) end (region-end)))
5102       ((org-on-heading-p)
5103	(setq beg (point) end (save-excursion (outline-next-heading) (point))))
5104       ((org-at-item-checkbox-p)
5105	(save-excursion
5106	  (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
5107	(throw 'exit t))
5108       (t (error "Not at a checkbox or heading, and no active region")))
5109      (save-excursion
5110	(goto-char beg)
5111	(while (< (point) end)
5112	  (when (org-at-item-checkbox-p)
5113	    (setq status (equal (match-string 0) "[X]"))
5114	    (when (eq firstnew 'unknown)
5115	      (setq firstnew (not status)))
5116	    (replace-match
5117	     (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5118	  (beginning-of-line 2)))))
5119  (org-update-checkbox-count-maybe))
5120
5121(defun org-update-checkbox-count-maybe ()
5122  "Update checkbox statistics unless turned off by user."
5123  (when org-provide-checkbox-statistics
5124    (org-update-checkbox-count)))
5125
5126(defun org-update-checkbox-count (&optional all)
5127  "Update the checkbox statistics in the current section.
5128This will find all statistic cookies like [57%] and [6/12] and update them
5129with the current numbers.  With optional prefix argument ALL, do this for
5130the whole buffer."
5131  (interactive "P")
5132  (save-excursion
5133    (let* ((buffer-invisibility-spec nil) ; Emacs 21 compatibility
5134	   (beg (progn (outline-back-to-heading) (point)))
5135	   (end (move-marker (make-marker)
5136			     (progn (outline-next-heading) (point))))
5137	   (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
5138	   (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)")
5139	   b1 e1 f1 c-on c-off lim (cstat 0))
5140      (when all
5141	(goto-char (point-min))
5142	(outline-next-heading)
5143	(setq beg (point) end (point-max)))
5144      (goto-char beg)
5145      (while (re-search-forward re end t)
5146	(setq cstat (1+ cstat)
5147	      b1 (match-beginning 0)
5148	      e1 (match-end 0)
5149	      f1 (match-beginning 1)
5150	      lim (cond
5151		   ((org-on-heading-p) (outline-next-heading) (point))
5152		   ((org-at-item-p) (org-end-of-item) (point))
5153		   (t nil))
5154	      c-on 0 c-off 0)
5155	(goto-char e1)
5156	(when lim
5157	  (while (re-search-forward re-box lim t)
5158	    (if (equal (match-string 2) "[ ]")
5159		(setq c-off (1+ c-off))
5160	      (setq c-on (1+ c-on))))
5161	  (delete-region b1 e1)
5162	  (goto-char b1)
5163	  (insert (if f1
5164		      (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5165		    (format "[%d/%d]" c-on (+ c-on c-off))))))
5166      (when (interactive-p)
5167	(message "Checkbox satistics updated %s (%d places)"
5168		 (if all "in entire file" "in current outline entry") cstat)))))
5169
5170(defun org-get-checkbox-statistics-face ()
5171  "Select the face for checkbox statistics.
5172The face will be `org-done' when all relevant boxes are checked.  Otherwise
5173it will be `org-todo'."
5174  (if (match-end 1)
5175      (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5176    (if (and (> (match-end 2) (match-beginning 2))
5177	     (equal (match-string 2) (match-string 3)))
5178	'org-done
5179      'org-todo)))
5180
5181(defun org-get-indentation (&optional line)
5182  "Get the indentation of the current line, interpreting tabs.
5183When LINE is given, assume it represents a line and compute its indentation."
5184  (if line
5185      (if (string-match "^ *" (org-remove-tabs line))
5186	  (match-end 0))
5187    (save-excursion
5188      (beginning-of-line 1)
5189      (skip-chars-forward " \t")
5190      (current-column))))
5191
5192(defun org-remove-tabs (s &optional width)
5193  "Replace tabulators in S with spaces.
5194Assumes that s is a single line, starting in column 0."
5195  (setq width (or width tab-width))
5196  (while (string-match "\t" s)
5197    (setq s (replace-match
5198	     (make-string
5199	      (- (* width (/ (+ (match-beginning 0) width) width))
5200		 (match-beginning 0)) ?\ )
5201	     t t s)))
5202  s)
5203
5204(defun org-fix-indentation (line ind)
5205  "Fix indentation in LINE.
5206IND is a cons cell with target and minimum indentation.
5207If the current indenation in LINE is smaller than the minimum,
5208leave it alone.  If it is larger than ind, set it to the target."
5209  (let* ((l (org-remove-tabs line))
5210	 (i (org-get-indentation l))
5211	 (i1 (car ind)) (i2 (cdr ind)))
5212    (if (>= i i2) (setq l (substring line i2)))
5213    (if (> i1 0)
5214	(concat (make-string i1 ?\ ) l)
5215      l)))
5216
5217(defun org-beginning-of-item ()
5218  "Go to the beginning of the current hand-formatted item.
5219If the cursor is not in an item, throw an error."
5220  (interactive)
5221  (let ((pos (point))
5222	(limit (save-excursion (org-back-to-heading)
5223			       (beginning-of-line 2) (point)))
5224	ind ind1)
5225    (if (org-at-item-p)
5226	(beginning-of-line 1)
5227      (beginning-of-line 1)
5228      (skip-chars-forward " \t")
5229      (setq ind (current-column))
5230      (if (catch 'exit
5231	    (while t
5232	      (beginning-of-line 0)
5233	      (if (< (point) limit) (throw 'exit nil))
5234	      (unless (looking-at "[ \t]*$")
5235		(skip-chars-forward " \t")
5236		(setq ind1 (current-column))
5237		(if (< ind1 ind)
5238		    (throw 'exit (org-at-item-p))))))
5239	  nil
5240	(goto-char pos)
5241	(error "Not in an item")))))
5242
5243(defun org-end-of-item ()
5244  "Go to the end of the current hand-formatted item.
5245If the cursor is not in an item, throw an error."
5246  (interactive)
5247  (let ((pos (point))
5248	(limit (save-excursion (outline-next-heading) (point)))
5249	(ind (save-excursion
5250	       (org-beginning-of-item)
5251	       (skip-chars-forward " \t")
5252	       (current-column)))
5253	ind1)
5254    (if (catch 'exit
5255	  (while t
5256	    (beginning-of-line 2)
5257	    (if (>= (point) limit) (throw 'exit t))
5258	    (unless (looking-at "[ \t]*$")
5259	      (skip-chars-forward " \t")
5260	      (setq ind1 (current-column))
5261	      (if (<= ind1 ind) (throw 'exit t)))))
5262	(beginning-of-line 1)
5263      (goto-char pos)
5264      (error "Not in an item"))))
5265
5266(defun org-next-item ()
5267  "Move to the beginning of the next item in the current plain list.
5268Error if not at a plain list, or if this is the last item in the list."
5269  (interactive)
5270  (let (ind ind1 (pos (point)))
5271    (org-beginning-of-item)
5272    (setq ind (org-get-indentation))
5273    (org-end-of-item)
5274    (setq ind1 (org-get-indentation))
5275    (unless (and (org-at-item-p) (= ind ind1))
5276      (goto-char pos)
5277      (error "On last item"))))
5278
5279(defun org-previous-item ()
5280  "Move to the beginning of the previous item in the current plain list.
5281Error if not at a plain list, or if this is the last item in the list."
5282  (interactive)
5283  (let (beg ind (pos (point)))
5284    (org-beginning-of-item)
5285    (setq beg (point))
5286    (setq ind (org-get-indentation))
5287    (goto-char beg)
5288    (catch 'exit
5289      (while t
5290	(beginning-of-line 0)
5291	(if (looking-at "[ \t]*$")
5292	    nil
5293	  (if (<= (org-get-indentation) ind)
5294	      (throw 'exit t)))))
5295    (condition-case nil
5296	(org-beginning-of-item)
5297      (error (goto-char pos)
5298	     (error "On first item")))))
5299
5300(defun org-move-item-down ()
5301  "Move the plain list item at point down, i.e. swap with following item.
5302Subitems (items with larger indentation) are considered part of the item,
5303so this really moves item trees."
5304  (interactive)
5305  (let (beg end ind ind1 (pos (point)) txt)
5306    (org-beginning-of-item)
5307    (setq beg (point))
5308    (setq ind (org-get-indentation))
5309    (org-end-of-item)
5310    (setq end (point))
5311    (setq ind1 (org-get-indentation))
5312    (if (and (org-at-item-p) (= ind ind1))
5313	(progn
5314	  (org-end-of-item)
5315	  (setq txt (buffer-substring beg end))
5316	  (save-excursion
5317	    (delete-region beg end))
5318	  (setq pos (point))
5319	  (insert txt)
5320	  (goto-char pos)
5321	  (org-maybe-renumber-ordered-list))
5322      (goto-char pos)
5323      (error "Cannot move this item further down"))))
5324
5325(defun org-move-item-up (arg)
5326  "Move the plain list item at point up, i.e. swap with previous item.
5327Subitems (items with larger indentation) are considered part of the item,
5328so this really moves item trees."
5329  (interactive "p")
5330  (let (beg end ind ind1 (pos (point)) txt)
5331    (org-beginning-of-item)
5332    (setq beg (point))
5333    (setq ind (org-get-indentation))
5334    (org-end-of-item)
5335    (setq end (point))
5336    (goto-char beg)
5337    (catch 'exit
5338      (while t
5339	(beginning-of-line 0)
5340	(if (looking-at "[ \t]*$")
5341	    nil
5342	  (if (<= (setq ind1 (org-get-indentation)) ind)
5343	      (throw 'exit t)))))
5344    (condition-case nil
5345	(org-beginning-of-item)
5346      (error (goto-char beg)
5347	     (error "Cannot move this item further up")))
5348    (setq ind1 (org-get-indentation))
5349    (if (and (org-at-item-p) (= ind ind1))
5350	(progn
5351	  (setq txt (buffer-substring beg end))
5352	  (save-excursion
5353	    (delete-region beg end))
5354	  (setq pos (point))
5355	  (insert txt)
5356	  (goto-char pos)
5357	  (org-maybe-renumber-ordered-list))
5358      (goto-char pos)
5359      (error "Cannot move this item further up"))))
5360
5361(defun org-maybe-renumber-ordered-list ()
5362  "Renumber the ordered list at point if setup allows it.
5363This tests the user option `org-auto-renumber-ordered-lists' before
5364doing the renumbering."
5365  (and org-auto-renumber-ordered-lists
5366       (org-at-item-p)
5367       (match-beginning 3)
5368       (org-renumber-ordered-list 1)))
5369
5370(defun org-get-string-indentation (s)
5371  "What indentation has S due to SPACE and TAB at the beginning of the string?"
5372  (let ((n -1) (i 0) (w tab-width) c)
5373    (catch 'exit
5374      (while (< (setq n (1+ n)) (length s))
5375	(setq c (aref s n))
5376	(cond ((= c ?\ ) (setq i (1+ i)))
5377	      ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5378	      (t (throw 'exit t)))))
5379    i))
5380
5381(defun org-renumber-ordered-list (arg)
5382  "Renumber an ordered plain list.
5383Cursor needs to be in the first line of an item, the line that starts
5384with something like \"1.\" or \"2)\"."
5385  (interactive "p")
5386  (unless (and (org-at-item-p)
5387	       (match-beginning 3))
5388    (error "This is not an ordered list"))
5389  (let ((line (org-current-line))
5390	(col (current-column))
5391	(ind (org-get-string-indentation
5392	      (buffer-substring (point-at-bol) (match-beginning 3))))
5393	;; (term (substring (match-string 3) -1))
5394	ind1 (n (1- arg)))
5395    ;; find where this list begins
5396    (catch 'exit
5397      (while t
5398	(catch 'next
5399	  (beginning-of-line 0)
5400	  (if (looking-at "[ \t]*$") (throw 'next t))
5401	  (skip-chars-forward " \t") (setq ind1 (current-column))
5402	  (if (or (< ind1 ind)
5403		  (and (= ind1 ind)
5404		       (not (org-at-item-p))))
5405	      (throw 'exit t)))))
5406    ;; Walk forward and replace these numbers
5407    (catch 'exit
5408      (while t
5409	(catch 'next
5410	  (beginning-of-line 2)
5411	  (if (eobp) (throw 'exit nil))
5412	  (if (looking-at "[ \t]*$") (throw 'next nil))
5413	  (skip-chars-forward " \t") (setq ind1 (current-column))
5414	  (if (> ind1 ind) (throw 'next t))
5415	  (if (< ind1 ind) (throw 'exit t))
5416	  (if (not (org-at-item-p)) (throw 'exit nil))
5417	  (if (not (match-beginning 3))
5418	      (error "unordered bullet in ordered list.  Press \\[undo] to recover"))
5419	  (delete-region (match-beginning 3) (1- (match-end 3)))
5420	  (goto-char (match-beginning 3))
5421	  (insert (format "%d" (setq n (1+ n)))))))
5422    (goto-line line)
5423    (move-to-column col)))
5424
5425(defvar org-last-indent-begin-marker (make-marker))
5426(defvar org-last-indent-end-marker (make-marker))
5427
5428(defun org-outdent-item (arg)
5429  "Outdent a local list item."
5430  (interactive "p")
5431  (org-indent-item (- arg)))
5432
5433(defun org-indent-item (arg)
5434  "Indent a local list item."
5435  (interactive "p")
5436  (unless (org-at-item-p)
5437    (error "Not on an item"))
5438  (save-excursion
5439    (let (beg end ind ind1)
5440      (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5441	  (setq beg org-last-indent-begin-marker
5442		end org-last-indent-end-marker)
5443	(org-beginning-of-item)
5444	(setq beg (move-marker org-last-indent-begin-marker (point)))
5445	(org-end-of-item)
5446	(setq end (move-marker org-last-indent-end-marker (point))))
5447      (goto-char beg)
5448      (skip-chars-forward " \t") (setq ind (current-column))
5449      (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
5450      (while (< (point) end)
5451	(beginning-of-line 1)
5452	(skip-chars-forward " \t") (setq ind1 (current-column))
5453	(delete-region (point-at-bol) (point))
5454	(indent-to-column (+ ind1 arg))
5455	(beginning-of-line 2)))))
5456
5457;;;; Archiving
5458
5459(defalias 'org-advertized-archive-subtree 'org-archive-subtree)
5460
5461(defun org-archive-subtree (&optional find-done)
5462  "Move the current subtree to the archive.
5463The archive can be a certain top-level heading in the current file, or in
5464a different file.  The tree will be moved to that location, the subtree
5465heading be marked DONE, and the current time will be added.
5466
5467When called with prefix argument FIND-DONE, find whole trees without any
5468open TODO items and archive them (after getting confirmation from the user).
5469If the cursor is not at a headline when this comand is called, try all level
54701 trees.  If the cursor is on a headline, only try the direct children of
5471this heading. "
5472  (interactive "P")
5473  (if find-done
5474      (org-archive-all-done)
5475    ;; Save all relevant TODO keyword-relatex variables
5476
5477    (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
5478	  (tr-org-todo-keywords org-todo-keywords)
5479	  (tr-org-todo-interpretation org-todo-interpretation)
5480	  (tr-org-done-string org-done-string)
5481	  (tr-org-todo-regexp org-todo-regexp)
5482	  (tr-org-todo-line-regexp org-todo-line-regexp)
5483	  (tr-org-odd-levels-only org-odd-levels-only)
5484	  (this-buffer (current-buffer))
5485	  (org-archive-location org-archive-location)
5486	  (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
5487	  file heading buffer level newfile-p)
5488
5489      ;; Try to find a local archive location
5490      (save-excursion
5491	(if (or (re-search-backward re nil t) (re-search-forward re nil t))
5492	    (setq org-archive-location (match-string 1))))
5493
5494      (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
5495	  (progn
5496	    (setq file (format (match-string 1 org-archive-location)
5497			       (file-name-nondirectory buffer-file-name))
5498		  heading (match-string 2 org-archive-location)))
5499	(error "Invalid `org-archive-location'"))
5500      (if (> (length file) 0)
5501	  (setq newfile-p (not (file-exists-p file))
5502		buffer (find-file-noselect file))
5503	(setq buffer (current-buffer)))
5504      (unless buffer
5505	(error "Cannot access file \"%s\"" file))
5506      (if (and (> (length heading) 0)
5507	       (string-match "^\\*+" heading))
5508	  (setq level (match-end 0))
5509	(setq heading nil level 0))
5510      (save-excursion
5511	;; We first only copy, in case something goes wrong
5512	;; we need to protect this-command, to avoid kill-region sets it,
5513	;; which would lead to duplication of subtrees
5514	(let (this-command) (org-copy-subtree))
5515	(set-buffer buffer)
5516	;; Enforce org-mode for the archive buffer
5517	(if (not (org-mode-p))
5518	    ;; Force the mode for future visits.
5519	    (let ((org-insert-mode-line-in-empty-file t))
5520	      (call-interactively 'org-mode)))
5521	(when newfile-p
5522	  (goto-char (point-max))
5523	  (insert (format "\nArchived entries from file %s\n\n"
5524			  (buffer-file-name this-buffer))))
5525	;; Force the TODO keywords of the original buffer
5526	(let ((org-todo-line-regexp tr-org-todo-line-regexp)
5527	      (org-todo-keywords tr-org-todo-keywords)
5528	      (org-todo-interpretation tr-org-todo-interpretation)
5529	      (org-done-string tr-org-done-string)
5530	      (org-todo-regexp tr-org-todo-regexp)
5531	      (org-todo-line-regexp tr-org-todo-line-regexp)
5532	      (org-odd-levels-only
5533	       (if (local-variable-p 'org-odd-levels-only)
5534		   org-odd-levels-only
5535		 tr-org-odd-levels-only)))
5536	  (goto-char (point-min))
5537	  (if heading
5538	      (progn
5539		(if (re-search-forward
5540		     (concat "\\(^\\|\r\\)"
5541			     (regexp-quote heading) "[ \t]*\\(:[a-zA-Z0-9_@:]+:\\)?[ \t]*\\($\\|\r\\)")
5542		     nil t)
5543		    (goto-char (match-end 0))
5544		  ;; Heading not found, just insert it at the end
5545		  (goto-char (point-max))
5546		  (or (bolp) (insert "\n"))
5547		  (insert "\n" heading "\n")
5548		  (end-of-line 0))
5549		;; Make the subtree visible
5550		(show-subtree)
5551		(org-end-of-subtree t)
5552		(skip-chars-backward " \t\r\n")
5553		(and (looking-at "[ \t\r\n]*")
5554		     (replace-match "\n\n")))
5555	    ;; No specific heading, just go to end of file.
5556	    (goto-char (point-max)) (insert "\n"))
5557	  ;; Paste
5558	  (org-paste-subtree (org-get-legal-level level 1))
5559	  ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
5560	  (if org-archive-mark-done
5561	      (let (org-log-done)
5562		(org-todo (length org-todo-keywords))))
5563	  ;; Move cursor to right after the TODO keyword
5564	  (when org-archive-stamp-time
5565	    (beginning-of-line 1)
5566	    (looking-at org-todo-line-regexp)
5567	    (goto-char (or (match-end 2) (match-beginning 3)))
5568	    (org-insert-time-stamp (org-current-time) t t "(" ")"))
5569	  ;; Save the buffer, if it is not the same buffer.
5570	  (if (not (eq this-buffer buffer)) (save-buffer))))
5571      ;; Here we are back in the original buffer.  Everything seems to have
5572      ;; worked.  So now cut the tree and finish up.
5573      (let (this-command) (org-cut-subtree))
5574      (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
5575      (message "Subtree archived %s"
5576	       (if (eq this-buffer buffer)
5577		   (concat "under heading: " heading)
5578		 (concat "in file: " (abbreviate-file-name file)))))))
5579
5580(defun org-archive-all-done (&optional tag)
5581  "Archive sublevels of the current tree without open TODO items.
5582If the cursor is not on a headline, try all level 1 trees.  If
5583it is on a headline, try all direct children.
5584When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
5585  (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
5586	(rea (concat ".*:" org-archive-tag ":"))
5587	(begm (make-marker))
5588	(endm (make-marker))
5589	(question (if tag "Set ARCHIVE tag (no open TODO items)? "
5590		    "Move subtree to archive (no open TODO items)? "))
5591	beg end (cntarch 0))
5592    (if (org-on-heading-p)
5593	(progn
5594	  (setq re1 (concat "^" (regexp-quote
5595				 (make-string
5596				  (1+ (- (match-end 0) (match-beginning 0)))
5597				  ?*))
5598			    " "))
5599	  (move-marker begm (point))
5600	  (move-marker endm (org-end-of-subtree t)))
5601      (setq re1 "^* ")
5602      (move-marker begm (point-min))
5603      (move-marker endm (point-max)))
5604    (save-excursion
5605      (goto-char begm)
5606      (while (re-search-forward re1 endm t)
5607	(setq beg (match-beginning 0)
5608	      end (save-excursion (org-end-of-subtree t) (point)))
5609	(goto-char beg)
5610	(if (re-search-forward re end t)
5611	    (goto-char end)
5612	  (goto-char beg)
5613	  (if (and (or (not tag) (not (looking-at rea)))
5614		   (y-or-n-p question))
5615	      (progn
5616		(if tag
5617		    (org-toggle-tag org-archive-tag 'on)
5618		  (org-archive-subtree))
5619		(setq cntarch (1+ cntarch)))
5620	    (goto-char end)))))
5621    (message "%d trees archived" cntarch)))
5622
5623(defun org-cycle-hide-archived-subtrees (state)
5624  "Re-hide all archived subtrees after a visibility state change."
5625  (when (and (not org-cycle-open-archived-trees)
5626             (not (memq state '(overview folded))))
5627    (save-excursion
5628      (let* ((globalp (memq state '(contents all)))
5629             (beg (if globalp (point-min) (point)))
5630             (end (if globalp (point-max) (org-end-of-subtree t))))
5631	(org-hide-archived-subtrees beg end)
5632	(goto-char beg)
5633	(if (looking-at (concat ".*:" org-archive-tag ":"))
5634	    (message (substitute-command-keys
5635		      "Subtree is archived and stays closed.  Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
5636
5637(defun org-force-cycle-archived ()
5638  "Cycle subtree even if it is archived."
5639  (interactive)
5640  (setq this-command 'org-cycle)
5641  (let ((org-cycle-open-archived-trees t))
5642    (call-interactively 'org-cycle)))
5643
5644(defun org-hide-archived-subtrees (beg end)
5645  "Re-hide all archived subtrees after a visibility state change."
5646  (save-excursion
5647    (let* ((re (concat ":" org-archive-tag ":")))
5648      (goto-char beg)
5649      (while (re-search-forward re end t)
5650	(and (org-on-heading-p) (hide-subtree))
5651	(org-end-of-subtree t)))))
5652
5653(defun org-toggle-tag (tag &optional onoff)
5654  "Toggle the tag TAG for the current line.
5655If ONOFF is `on' or `off', don't toggle but set to this state."
5656  (unless (org-on-heading-p) (error "Not on headling"))
5657  (let (res current)
5658    (save-excursion
5659      (beginning-of-line)
5660      (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
5661			     (point-at-eol) t)
5662	  (progn
5663	    (setq current (match-string 1))
5664	    (replace-match ""))
5665	(setq current ""))
5666      (setq current (nreverse (org-split-string current ":")))
5667      (cond
5668       ((eq onoff 'on)
5669	(setq res t)
5670	(or (member tag current) (push tag current)))
5671       ((eq onoff 'off)
5672	(or (not (member tag current)) (setq current (delete tag current))))
5673       (t (if (member tag current)
5674	      (setq current (delete tag current))
5675	    (setq res t)
5676	    (push tag current))))
5677      (end-of-line 1)
5678      (when current
5679	(insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
5680      (org-set-tags nil t))
5681    res))
5682
5683(defun org-toggle-archive-tag (&optional arg)
5684  "Toggle the archive tag for the current headline.
5685With prefix ARG, check all children of current headline and offer tagging
5686the children that do not contain any open TODO items."
5687  (interactive "P")
5688  (if arg
5689      (org-archive-all-done 'tag)
5690    (let (set)
5691      (save-excursion
5692	(org-back-to-heading t)
5693	(setq set (org-toggle-tag org-archive-tag))
5694	(when set (hide-subtree)))
5695      (and set (beginning-of-line 1))
5696      (message "Subtree %s" (if set "archived" "unarchived")))))
5697
5698
5699;;;; Tables
5700
5701;;; The table editor
5702
5703;; Watch out:  Here we are talking about two different kind of tables.
5704;; Most of the code is for the tables created with the Org-mode table editor.
5705;; Sometimes, we talk about tables created and edited with the table.el
5706;; Emacs package.  We call the former org-type tables, and the latter
5707;; table.el-type tables.
5708
5709(defun org-before-change-function (beg end)
5710  "Every change indicates that a table might need an update."
5711  (setq org-table-may-need-update t))
5712
5713(defconst org-table-line-regexp "^[ \t]*|"
5714  "Detects an org-type table line.")
5715(defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5716  "Detects an org-type table line.")
5717(defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
5718  "Detects a table line marked for automatic recalculation.")
5719(defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
5720  "Detects a table line marked for automatic recalculation.")
5721(defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
5722  "Detects a table line marked for automatic recalculation.")
5723(defconst org-table-hline-regexp "^[ \t]*|-"
5724  "Detects an org-type table hline.")
5725(defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5726  "Detects a table-type table hline.")
5727(defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5728  "Detects an org-type or table-type table.")
5729(defconst org-table-border-regexp "^[ \t]*[^| \t]"
5730  "Searching from within a table (any type) this finds the first line
5731outside the table.")
5732(defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5733  "Searching from within a table (any type) this finds the first line
5734outside the table.")
5735
5736(defvar org-table-last-highlighted-reference nil)
5737(defvar org-table-formula-history nil)
5738
5739(defvar org-table-column-names nil
5740  "Alist with column names, derived from the `!' line.")
5741(defvar org-table-column-name-regexp nil
5742  "Regular expression matching the current column names.")
5743(defvar org-table-local-parameters nil
5744  "Alist with parameter names, derived from the `$' line.")
5745(defvar org-table-named-field-locations nil
5746  "Alist with locations of named fields.")
5747
5748(defvar org-table-current-line-types nil
5749  "Table row types, non-nil only for the duration of a comand.")
5750(defvar org-table-current-begin-line nil
5751  "Table begin line, non-nil only for the duration of a comand.")
5752(defvar org-table-dlines nil
5753  "Vector of data line line numbers in the current table.")
5754(defvar org-table-hlines nil
5755  "Vector of hline line numbers in the current table.")
5756
5757(defconst org-table-range-regexp
5758   "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
5759   ;;   1                        2                    3          4                        5
5760  "Regular expression for matching ranges in formulas.")
5761
5762(defconst org-table-range-regexp2
5763   "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[a-zA-Z0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[a-zA-Z0-9]+\\)?\\)?\\|\\$[a-zA-Z0-9]+\\.\\.\\$[a-zA-Z0-9]+"
5764  "Regular expression to recognize ranges in formulas for highlighting.")
5765
5766(defvar org-inhibit-highlight-removal nil)
5767
5768
5769(defun org-table-create-with-table.el ()
5770  "Use the table.el package to insert a new table.
5771If there is already a table at point, convert between Org-mode tables
5772and table.el tables."
5773  (interactive)
5774  (require 'table)
5775  (cond
5776   ((org-at-table.el-p)
5777    (if (y-or-n-p "Convert table to Org-mode table? ")
5778	(org-table-convert)))
5779   ((org-at-table-p)
5780    (if (y-or-n-p "Convert table to table.el table? ")
5781	(org-table-convert)))
5782   (t (call-interactively 'table-insert))))
5783
5784(defun org-table-create-or-convert-from-region (arg)
5785  "Convert region to table, or create an empty table.
5786If there is an active region, convert it to a table.  If there is no such
5787region, create an empty table."
5788  (interactive "P")
5789  (if (org-region-active-p)
5790      (org-table-convert-region (region-beginning) (region-end) arg)
5791    (org-table-create arg)))
5792
5793(defun org-table-create (&optional size)
5794  "Query for a size and insert a table skeleton.
5795SIZE is a string Columns x Rows like for example \"3x2\"."
5796  (interactive "P")
5797  (unless size
5798    (setq size (read-string
5799		(concat "Table size Columns x Rows [e.g. "
5800			org-table-default-size "]: ")
5801		"" nil org-table-default-size)))
5802
5803  (let* ((pos (point))
5804	 (indent (make-string (current-column) ?\ ))
5805	 (split (org-split-string size " *x *"))
5806	 (rows (string-to-number (nth 1 split)))
5807	 (columns (string-to-number (car split)))
5808	 (line (concat (apply 'concat indent "|" (make-list columns "  |"))
5809		       "\n")))
5810    (if (string-match "^[ \t]*$" (buffer-substring-no-properties
5811				  (point-at-bol) (point)))
5812	(beginning-of-line 1)
5813      (newline))
5814    ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
5815    (dotimes (i rows) (insert line))
5816    (goto-char pos)
5817    (if (> rows 1)
5818	;; Insert a hline after the first row.
5819	(progn
5820	  (end-of-line 1)
5821	  (insert "\n|-")
5822	  (goto-char pos)))
5823    (org-table-align)))
5824
5825(defun org-table-convert-region (beg0 end0 &optional nspace)
5826  "Convert region to a table.
5827The region goes from BEG0 to END0, but these borders will be moved
5828slightly, to make sure a beginning of line in the first line is included.
5829When NSPACE is non-nil, it indicates the minimum number of spaces that
5830separate columns (default: just one space)."
5831  (interactive "rP")
5832  (let* ((beg (min beg0 end0))
5833	 (end (max beg0 end0))
5834	 (tabsep t)
5835	 re)
5836    (goto-char beg)
5837    (beginning-of-line 1)
5838    (setq beg (move-marker (make-marker) (point)))
5839    (goto-char end)
5840    (if (bolp) (backward-char 1) (end-of-line 1))
5841    (setq end (move-marker (make-marker) (point)))
5842    ;; Lets see if this is tab-separated material.  If every nonempty line
5843    ;; contains a tab, we will assume that it is tab-separated material
5844    (if nspace
5845	(setq tabsep nil)
5846      (goto-char beg)
5847      (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
5848    (if nspace (setq tabsep nil))
5849    (if tabsep
5850	(setq re "^\\|\t")
5851      (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
5852		       (max 1 (prefix-numeric-value nspace)))))
5853    (goto-char beg)
5854    (while (re-search-forward re end t)
5855      (replace-match "| " t t))
5856    (goto-char beg)
5857    (insert " ")
5858    (org-table-align)))
5859
5860(defun org-table-import (file arg)
5861  "Import FILE as a table.
5862The file is assumed to be tab-separated.  Such files can be produced by most
5863spreadsheet and database applications.  If no tabs (at least one per line)
5864are found, lines will be split on whitespace into fields."
5865  (interactive "f\nP")
5866  (or (bolp) (newline))
5867  (let ((beg (point))
5868	(pm (point-max)))
5869    (insert-file-contents file)
5870    (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
5871
5872(defun org-table-export ()
5873  "Export table as a tab-separated file.
5874Such a file can be imported into a spreadsheet program like Excel."
5875  (interactive)
5876  (let* ((beg (org-table-begin))
5877	 (end (org-table-end))
5878	 (table (buffer-substring beg end))
5879	 (file (read-file-name "Export table to: "))
5880	 buf)
5881    (unless (or (not (file-exists-p file))
5882		(y-or-n-p (format "Overwrite file %s? " file)))
5883      (error "Abort"))
5884    (with-current-buffer (find-file-noselect file)
5885      (setq buf (current-buffer))
5886      (erase-buffer)
5887      (fundamental-mode)
5888      (insert table)
5889      (goto-char (point-min))
5890      (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
5891	(replace-match "" t t)
5892	(end-of-line 1))
5893      (goto-char (point-min))
5894      (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
5895	(replace-match "" t t)
5896	(goto-char (min (1+ (point)) (point-max))))
5897      (goto-char (point-min))
5898      (while (re-search-forward "^-[-+]*$" nil t)
5899	(replace-match "")
5900	(if (looking-at "\n")
5901	    (delete-char 1)))
5902      (goto-char (point-min))
5903      (while (re-search-forward "[ \t]*|[ \t]*" nil t)
5904	(replace-match "\t" t t))
5905      (save-buffer))
5906    (kill-buffer buf)))
5907
5908(defvar org-table-aligned-begin-marker (make-marker)
5909  "Marker at the beginning of the table last aligned.
5910Used to check if cursor still is in that table, to minimize realignment.")
5911(defvar org-table-aligned-end-marker (make-marker)
5912  "Marker at the end of the table last aligned.
5913Used to check if cursor still is in that table, to minimize realignment.")
5914(defvar org-table-last-alignment nil
5915  "List of flags for flushright alignment, from the last re-alignment.
5916This is being used to correctly align a single field after TAB or RET.")
5917(defvar org-table-last-column-widths nil
5918  "List of max width of fields in each column.
5919This is being used to correctly align a single field after TAB or RET.")
5920(defvar org-table-overlay-coordinates nil
5921  "Overlay coordinates after each align of a table.")
5922(make-variable-buffer-local 'org-table-overlay-coordinates)
5923
5924(defvar org-last-recalc-line nil)
5925(defconst org-narrow-column-arrow "=>"
5926  "Used as display property in narrowed table columns.")
5927
5928(defun org-table-align ()
5929  "Align the table at point by aligning all vertical bars."
5930  (interactive)
5931  (let* (
5932	 ;; Limits of table
5933	 (beg (org-table-begin))
5934	 (end (org-table-end))
5935	 ;; Current cursor position
5936	 (linepos (org-current-line))
5937	 (colpos (org-table-current-column))
5938	 (winstart (window-start))
5939	 (winstartline (org-current-line (min winstart (1- (point-max)))))
5940	 lines (new "") lengths l typenums ty fields maxfields i
5941	 column
5942	 (indent "") cnt frac
5943	 rfmt hfmt
5944	 (spaces '(1 . 1))
5945	 (sp1 (car spaces))
5946	 (sp2 (cdr spaces))
5947	 (rfmt1 (concat
5948		 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
5949	 (hfmt1 (concat
5950		 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
5951	 emptystrings links dates narrow fmax f1 len c e)
5952    (untabify beg end)
5953    (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
5954    ;; Check if we have links or dates
5955    (goto-char beg)
5956    (setq links (re-search-forward org-bracket-link-regexp end t))
5957    (goto-char beg)
5958    (setq dates (and org-display-custom-times
5959		     (re-search-forward org-ts-regexp-both end t)))
5960    ;; Make sure the link properties are right
5961    (when links (goto-char beg) (while (org-activate-bracket-links end)))
5962    ;; Make sure the date properties are right
5963    (when dates (goto-char beg) (while (org-activate-dates end)))
5964
5965    ;; Check if we are narrowing any columns
5966    (goto-char beg)
5967    (setq narrow (and org-format-transports-properties-p
5968		      (re-search-forward "<[0-9]+>" end t)))
5969    ;; Get the rows
5970    (setq lines (org-split-string
5971		 (buffer-substring beg end) "\n"))
5972    ;; Store the indentation of the first line
5973    (if (string-match "^ *" (car lines))
5974	(setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
5975    ;; Mark the hlines by setting the corresponding element to nil
5976    ;; At the same time, we remove trailing space.
5977    (setq lines (mapcar (lambda (l)
5978			  (if (string-match "^ *|-" l)
5979			      nil
5980			    (if (string-match "[ \t]+$" l)
5981				(substring l 0 (match-beginning 0))
5982			      l)))
5983			lines))
5984    ;; Get the data fields by splitting the lines.
5985    (setq fields (mapcar
5986		  (lambda (l)
5987		      (org-split-string l " *| *"))
5988		  (delq nil (copy-sequence lines))))
5989    ;; How many fields in the longest line?
5990    (condition-case nil
5991	(setq maxfields (apply 'max (mapcar 'length fields)))
5992      (error
5993       (kill-region beg end)
5994       (org-table-create org-table-default-size)
5995       (error "Empty table - created default table")))
5996    ;; A list of empty strings to fill any short rows on output
5997    (setq emptystrings (make-list maxfields ""))
5998    ;; Check for special formatting.
5999    (setq i -1)
6000    (while (< (setq i (1+ i)) maxfields)   ;; Loop over all columns
6001      (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
6002      ;; Check if there is an explicit width specified
6003      (when narrow
6004	(setq c column fmax nil)
6005	(while c
6006	  (setq e (pop c))
6007	  (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
6008	      (setq fmax (string-to-number (match-string 1 e)) c nil)))
6009	;; Find fields that are wider than fmax, and shorten them
6010	(when fmax
6011	  (loop for xx in column do
6012		(when (and (stringp xx)
6013			   (> (org-string-width xx) fmax))
6014		  (org-add-props xx nil
6015		    'help-echo
6016		    (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
6017		  (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
6018		  (unless (> f1 1)
6019		    (error "Cannot narrow field starting with wide link \"%s\""
6020			   (match-string 0 xx)))
6021		  (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
6022		  (add-text-properties (- f1 2) f1
6023				       (list 'display org-narrow-column-arrow)
6024				       xx)))))
6025      ;; Get the maximum width for each column
6026      (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
6027      ;; Get the fraction of numbers, to decide about alignment of the column
6028      (setq cnt 0 frac 0.0)
6029      (loop for x in column do
6030	    (if (equal x "")
6031		nil
6032	      (setq frac ( / (+ (* frac cnt)
6033				(if (string-match org-table-number-regexp x) 1 0))
6034			     (setq cnt (1+ cnt))))))
6035      (push (>= frac org-table-number-fraction) typenums))
6036    (setq lengths (nreverse lengths) typenums (nreverse typenums))
6037
6038    ;; Store the alignment of this table, for later editing of single fields
6039    (setq org-table-last-alignment typenums
6040	  org-table-last-column-widths lengths)
6041
6042    ;; With invisible characters, `format' does not get the field width right
6043    ;; So we need to make these fields wide by hand.
6044    (when links
6045      (loop for i from 0 upto (1- maxfields) do
6046	    (setq len (nth i lengths))
6047	    (loop for j from 0 upto (1- (length fields)) do
6048		  (setq c (nthcdr i (car (nthcdr j fields))))
6049		  (if (and (stringp (car c))
6050			   (string-match org-bracket-link-regexp (car c))
6051			   (< (org-string-width (car c)) len))
6052		      (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
6053
6054    ;; Compute the formats needed for output of the table
6055    (setq rfmt (concat indent "|") hfmt (concat indent "|"))
6056    (while (setq l (pop lengths))
6057      (setq ty (if (pop typenums) "" "-")) ; number types flushright
6058      (setq rfmt (concat rfmt (format rfmt1 ty l))
6059	    hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
6060    (setq rfmt (concat rfmt "\n")
6061	  hfmt (concat (substring hfmt 0 -1) "|\n"))
6062
6063    (setq new (mapconcat
6064	       (lambda (l)
6065		 (if l (apply 'format rfmt
6066			      (append (pop fields) emptystrings))
6067		   hfmt))
6068	       lines ""))
6069    ;; Replace the old one
6070    (delete-region beg end)
6071    (move-marker end nil)
6072    (move-marker org-table-aligned-begin-marker (point))
6073    (insert new)
6074    (move-marker org-table-aligned-end-marker (point))
6075    (when (and orgtbl-mode (not (org-mode-p)))
6076      (goto-char org-table-aligned-begin-marker)
6077      (while (org-hide-wide-columns org-table-aligned-end-marker)))
6078    ;; Try to move to the old location
6079    (goto-line winstartline)
6080    (setq winstart (point-at-bol))
6081    (goto-line linepos)
6082    (set-window-start (selected-window) winstart 'noforce)
6083    (org-table-goto-column colpos)
6084    (and org-table-overlay-coordinates (org-table-overlay-coordinates))
6085    (setq org-table-may-need-update nil)
6086    ))
6087
6088(defun org-string-width (s)
6089  "Compute width of string, ignoring invisible characters.
6090This ignores character with invisibility property `org-link', and also
6091characters with property `org-cwidth', because these will become invisible
6092upon the next fontification round."
6093  (let (b l)
6094    (when (or (eq t buffer-invisibility-spec)
6095	      (assq 'org-link buffer-invisibility-spec))
6096      (while (setq b (text-property-any 0 (length s)
6097					'invisible 'org-link s))
6098	(setq s (concat (substring s 0 b)
6099			(substring s (or (next-single-property-change
6100					  b 'invisible s) (length s)))))))
6101    (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
6102      (setq s (concat (substring s 0 b)
6103		      (substring s (or (next-single-property-change
6104					b 'org-cwidth s) (length s))))))
6105    (setq l (string-width s) b -1)
6106    (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
6107      (setq l (- l (get-text-property b 'org-dwidth-n s))))
6108    l))
6109
6110(defun org-table-begin (&optional table-type)
6111  "Find the beginning of the table and return its position.
6112With argument TABLE-TYPE, go to the beginning of a table.el-type table."
6113  (save-excursion
6114    (if (not (re-search-backward
6115	      (if table-type org-table-any-border-regexp
6116		org-table-border-regexp)
6117	      nil t))
6118	(progn (goto-char (point-min)) (point))
6119      (goto-char (match-beginning 0))
6120      (beginning-of-line 2)
6121      (point))))
6122
6123(defun org-table-end (&optional table-type)
6124  "Find the end of the table and return its position.
6125With argument TABLE-TYPE, go to the end of a table.el-type table."
6126  (save-excursion
6127    (if (not (re-search-forward
6128	      (if table-type org-table-any-border-regexp
6129		org-table-border-regexp)
6130	      nil t))
6131	(goto-char (point-max))
6132      (goto-char (match-beginning 0)))
6133    (point-marker)))
6134
6135(defun org-table-justify-field-maybe (&optional new)
6136  "Justify the current field, text to left, number to right.
6137Optional argument NEW may specify text to replace the current field content."
6138  (cond
6139   ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
6140   ((org-at-table-hline-p))
6141   ((and (not new)
6142	 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
6143			 (current-buffer)))
6144	     (< (point) org-table-aligned-begin-marker)
6145	     (>= (point) org-table-aligned-end-marker)))
6146    ;; This is not the same table, force a full re-align
6147    (setq org-table-may-need-update t))
6148   (t ;; realign the current field, based on previous full realign
6149    (let* ((pos (point)) s
6150	   (col (org-table-current-column))
6151	   (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
6152	   l f n o e)
6153      (when (> col 0)
6154	(skip-chars-backward "^|\n")
6155	(if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
6156	    (progn
6157	      (setq s (match-string 1)
6158		    o (match-string 0)
6159		    l (max 1 (- (match-end 0) (match-beginning 0) 3))
6160		    e (not (= (match-beginning 2) (match-end 2))))
6161	      (setq f (format (if num " %%%ds %s" " %%-%ds %s")
6162			      l (if e "|" (setq org-table-may-need-update t) ""))
6163		    n (format f s))
6164	      (if new
6165		  (if (<= (length new) l)      ;; FIXME: length -> str-width?
6166		      (setq n (format f new))
6167		    (setq n (concat new "|") org-table-may-need-update t)))
6168	      (or (equal n o)
6169		  (let (org-table-may-need-update)
6170		    (replace-match n))))
6171	  (setq org-table-may-need-update t))
6172	(goto-char pos))))))
6173
6174(defun org-table-next-field ()
6175  "Go to the next field in the current table, creating new lines as needed.
6176Before doing so, re-align the table if necessary."
6177  (interactive)
6178  (org-table-maybe-eval-formula)
6179  (org-table-maybe-recalculate-line)
6180  (if (and org-table-automatic-realign
6181	   org-table-may-need-update)
6182      (org-table-align))
6183  (let ((end (org-table-end)))
6184    (if (org-at-table-hline-p)
6185	(end-of-line 1))
6186    (condition-case nil
6187	(progn
6188	  (re-search-forward "|" end)
6189	  (if (looking-at "[ \t]*$")
6190	      (re-search-forward "|" end))
6191	  (if (and (looking-at "-")
6192		   org-table-tab-jumps-over-hlines
6193		   (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
6194	      (goto-char (match-beginning 1)))
6195	  (if (looking-at "-")
6196	      (progn
6197		(beginning-of-line 0)
6198		(org-table-insert-row 'below))
6199	    (if (looking-at " ") (forward-char 1))))
6200      (error
6201       (org-table-insert-row 'below)))))
6202
6203(defun org-table-previous-field ()
6204  "Go to the previous field in the table.
6205Before doing so, re-align the table if necessary."
6206  (interactive)
6207  (org-table-justify-field-maybe)
6208  (org-table-maybe-recalculate-line)
6209  (if (and org-table-automatic-realign
6210	   org-table-may-need-update)
6211      (org-table-align))
6212  (if (org-at-table-hline-p)
6213      (end-of-line 1))
6214  (re-search-backward "|" (org-table-begin))
6215  (re-search-backward "|" (org-table-begin))
6216  (while (looking-at "|\\(-\\|[ \t]*$\\)")
6217    (re-search-backward "|" (org-table-begin)))
6218  (if (looking-at "| ?")
6219      (goto-char (match-end 0))))
6220
6221(defun org-table-next-row ()
6222  "Go to the next row (same column) in the current table.
6223Before doing so, re-align the table if necessary."
6224  (interactive)
6225  (org-table-maybe-eval-formula)
6226  (org-table-maybe-recalculate-line)
6227  (if (or (looking-at "[ \t]*$")
6228	  (save-excursion (skip-chars-backward " \t") (bolp)))
6229      (newline)
6230    (if (and org-table-automatic-realign
6231	     org-table-may-need-update)
6232	(org-table-align))
6233    (let ((col (org-table-current-column)))
6234      (beginning-of-line 2)
6235      (if (or (not (org-at-table-p))
6236	      (org-at-table-hline-p))
6237	  (progn
6238	    (beginning-of-line 0)
6239	    (org-table-insert-row 'below)))
6240      (org-table-goto-column col)
6241      (skip-chars-backward "^|\n\r")
6242      (if (looking-at " ") (forward-char 1)))))
6243
6244(defun org-table-copy-down (n)
6245  "Copy a field down in the current column.
6246If the field at the cursor is empty, copy into it the content of the nearest
6247non-empty field above.  With argument N, use the Nth non-empty field.
6248If the current field is not empty, it is copied down to the next row, and
6249the cursor is moved with it.  Therefore, repeating this command causes the
6250column to be filled row-by-row.
6251If the variable `org-table-copy-increment' is non-nil and the field is an
6252integer, it will be incremented while copying."
6253  (interactive "p")
6254  (let* ((colpos (org-table-current-column))
6255	 (field (org-table-get-field))
6256	 (non-empty (string-match "[^ \t]" field))
6257	 (beg (org-table-begin))
6258	 txt)
6259    (org-table-check-inside-data-field)
6260    (if non-empty
6261	(progn
6262	  (setq txt (org-trim field))
6263	  (org-table-next-row)
6264	  (org-table-blank-field))
6265      (save-excursion
6266	(setq txt
6267	      (catch 'exit
6268		(while (progn (beginning-of-line 1)
6269			      (re-search-backward org-table-dataline-regexp
6270						  beg t))
6271		  (org-table-goto-column colpos t)
6272		  (if (and (looking-at
6273			    "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
6274			   (= (setq n (1- n)) 0))
6275		      (throw 'exit (match-string 1))))))))
6276    (if txt
6277	(progn
6278	  (if (and org-table-copy-increment
6279		   (string-match "^[0-9]+$" txt))
6280	      (setq txt (format "%d" (+ (string-to-number txt) 1))))
6281	  (insert txt)
6282	  (org-table-maybe-recalculate-line)
6283	  (org-table-align))
6284      (error "No non-empty field found"))))
6285
6286(defun org-table-check-inside-data-field ()
6287  "Is point inside a table data field?
6288I.e. not on a hline or before the first or after the last column?
6289This actually throws an error, so it aborts the current command."
6290  (if (or (not (org-at-table-p))
6291	  (= (org-table-current-column) 0)
6292	  (org-at-table-hline-p)
6293	  (looking-at "[ \t]*$"))
6294      (error "Not in table data field")))
6295
6296(defvar org-table-clip nil
6297  "Clipboard for table regions.")
6298
6299(defun org-table-blank-field ()
6300  "Blank the current table field or active region."
6301  (interactive)
6302  (org-table-check-inside-data-field)
6303  (if (and (interactive-p) (org-region-active-p))
6304      (let (org-table-clip)
6305	(org-table-cut-region (region-beginning) (region-end)))
6306    (skip-chars-backward "^|")
6307    (backward-char 1)
6308    (if (looking-at "|[^|\n]+")
6309	(let* ((pos (match-beginning 0))
6310	       (match (match-string 0))
6311	       (len (org-string-width match)))
6312	  (replace-match (concat "|" (make-string (1- len) ?\ )))
6313	  (goto-char (+ 2 pos))
6314	  (substring match 1)))))
6315
6316(defun org-table-get-field (&optional n replace)
6317  "Return the value of the field in column N of current row.
6318N defaults to current field.
6319If REPLACE is a string, replace field with this value.  The return value
6320is always the old value."
6321  (and n (org-table-goto-column n))
6322  (skip-chars-backward "^|\n")
6323  (backward-char 1)
6324  (if (looking-at "|[^|\r\n]*")
6325      (let* ((pos (match-beginning 0))
6326	     (val (buffer-substring (1+ pos) (match-end 0))))
6327	(if replace
6328	    (replace-match (concat "|" replace) t t))
6329	(goto-char (min (point-at-eol) (+ 2 pos)))
6330	val)
6331    (forward-char 1) ""))
6332
6333
6334(defun org-table-field-info (arg)
6335  "Show info about the current field, and highlight any reference at point."
6336  (interactive "P")
6337  (org-table-get-specials)
6338  (save-excursion
6339    (let* ((pos (point))
6340	   (col (org-table-current-column))
6341	   (cname (car (rassoc (int-to-string col) org-table-column-names)))
6342	   (name (car (rassoc (list (org-current-line) col)
6343			      org-table-named-field-locations)))
6344	   (eql (org-table-get-stored-formulas))
6345	   (dline (org-table-current-dline))
6346	   (ref (format "@%d$%d" dline col))
6347	   (fequation (or (assoc name eql) (assoc ref eql)))
6348	   (cequation (assoc (int-to-string col) eql)))
6349      (goto-char pos)
6350      (condition-case nil
6351	  (org-show-reference 'local)
6352	(error nil))
6353      (message "line @%d, col $%s%s, ref @%d$%d%s%s"
6354	       dline col
6355	       (if cname (concat " or $" cname) "")
6356	       dline col
6357	       (if name (concat " or $" name) "")
6358	       ;; FIXME: formula info not correct if special table line
6359	       (if (or fequation cequation)
6360		   (concat ", " (if fequation "field" "column")
6361			   " formula applies" "")
6362		 "")))))
6363
6364(defun org-table-current-column ()
6365  "Find out which column we are in.
6366When called interactively, column is also displayed in echo area."
6367  (interactive)
6368  (if (interactive-p) (org-table-check-inside-data-field))
6369  (save-excursion
6370    (let ((cnt 0) (pos (point)))
6371      (beginning-of-line 1)
6372      (while (search-forward "|" pos t)
6373	(setq cnt (1+ cnt)))
6374      (if (interactive-p) (message "This is table column %d" cnt))
6375      cnt)))
6376
6377(defun org-table-current-dline ()
6378  "Find out what table data line we are in.
6379Only datalins count for this."
6380  (interactive)
6381  (if (interactive-p) (org-table-check-inside-data-field))
6382  (save-excursion
6383    (let ((cnt 0) (pos (point)))
6384      (goto-char (org-table-begin))
6385      (while (<= (point) pos)
6386	(if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
6387	(beginning-of-line 2))
6388      (if (interactive-p) (message "This is table line %d" cnt))
6389      cnt)))
6390
6391(defun org-table-goto-column (n &optional on-delim force)
6392  "Move the cursor to the Nth column in the current table line.
6393With optional argument ON-DELIM, stop with point before the left delimiter
6394of the field.
6395If there are less than N fields, just go to after the last delimiter.
6396However, when FORCE is non-nil, create new columns if necessary."
6397  (interactive "p")
6398  (let ((pos (point-at-eol)))
6399    (beginning-of-line 1)
6400    (when (> n 0)
6401      (while (and (> (setq n (1- n)) -1)
6402		  (or (search-forward "|" pos t)
6403		      (and force
6404			   (progn (end-of-line 1)
6405				  (skip-chars-backward "^|")
6406				  (insert " | "))))))
6407;                                  (backward-char 2) t)))))
6408      (when (and force (not (looking-at ".*|")))
6409	(save-excursion (end-of-line 1) (insert " | ")))
6410      (if on-delim
6411	  (backward-char 1)
6412	(if (looking-at " ") (forward-char 1))))))
6413
6414(defun org-at-table-p (&optional table-type)
6415  "Return t if the cursor is inside an org-type table.
6416If TABLE-TYPE is non-nil, also check for table.el-type tables."
6417  (if org-enable-table-editor
6418      (save-excursion
6419	(beginning-of-line 1)
6420	(looking-at (if table-type org-table-any-line-regexp
6421		      org-table-line-regexp)))
6422    nil))
6423
6424(defun org-at-table.el-p ()
6425  "Return t if and only if we are at a table.el table."
6426  (and (org-at-table-p 'any)
6427       (save-excursion
6428	 (goto-char (org-table-begin 'any))
6429	 (looking-at org-table1-hline-regexp))))
6430
6431(defun org-table-recognize-table.el ()
6432  "If there is a table.el table nearby, recognize it and move into it."
6433  (if org-table-tab-recognizes-table.el
6434      (if (org-at-table.el-p)
6435	  (progn
6436	    (beginning-of-line 1)
6437	    (if (looking-at org-table-dataline-regexp)
6438		nil
6439	      (if (looking-at org-table1-hline-regexp)
6440		  (progn
6441		    (beginning-of-line 2)
6442		    (if (looking-at org-table-any-border-regexp)
6443			(beginning-of-line -1)))))
6444	    (if (re-search-forward "|" (org-table-end t) t)
6445		(progn
6446		  (require 'table)
6447		  (if (table--at-cell-p (point))
6448		      t
6449		    (message "recognizing table.el table...")
6450		    (table-recognize-table)
6451		    (message "recognizing table.el table...done")))
6452	      (error "This should not happen..."))
6453	    t)
6454	nil)
6455    nil))
6456
6457(defun org-at-table-hline-p ()
6458  "Return t if the cursor is inside a hline in a table."
6459  (if org-enable-table-editor
6460      (save-excursion
6461	(beginning-of-line 1)
6462	(looking-at org-table-hline-regexp))
6463    nil))
6464
6465(defun org-table-insert-column ()
6466  "Insert a new column into the table."
6467  (interactive)
6468  (if (not (org-at-table-p))
6469      (error "Not at a table"))
6470  (org-table-find-dataline)
6471  (let* ((col (max 1 (org-table-current-column)))
6472	 (beg (org-table-begin))
6473	 (end (org-table-end))
6474	 ;; Current cursor position
6475	 (linepos (org-current-line))
6476	 (colpos col))
6477    (goto-char beg)
6478    (while (< (point) end)
6479      (if (org-at-table-hline-p)
6480	  nil
6481	(org-table-goto-column col t)
6482	(insert "|   "))
6483      (beginning-of-line 2))
6484    (move-marker end nil)
6485    (goto-line linepos)
6486    (org-table-goto-column colpos)
6487    (org-table-align)
6488    (org-table-fix-formulas "$" nil (1- col) 1)))
6489
6490(defun org-table-find-dataline ()
6491  "Find a dataline in the current table, which is needed for column commands."
6492  (if (and (org-at-table-p)
6493	   (not (org-at-table-hline-p)))
6494      t
6495    (let ((col (current-column))
6496	  (end (org-table-end)))
6497      (move-to-column col)
6498      (while (and (< (point) end)
6499		  (or (not (= (current-column) col))
6500		      (org-at-table-hline-p)))
6501	(beginning-of-line 2)
6502	(move-to-column col))
6503      (if (and (org-at-table-p)
6504	       (not (org-at-table-hline-p)))
6505	  t
6506	(error
6507	 "Please position cursor in a data line for column operations")))))
6508
6509(defun org-table-delete-column ()
6510  "Delete a column from the table."
6511  (interactive)
6512  (if (not (org-at-table-p))
6513      (error "Not at a table"))
6514  (org-table-find-dataline)
6515  (org-table-check-inside-data-field)
6516  (let* ((col (org-table-current-column))
6517	 (beg (org-table-begin))
6518	 (end (org-table-end))
6519	 ;; Current cursor position
6520	 (linepos (org-current-line))
6521	 (colpos col))
6522    (goto-char beg)
6523    (while (< (point) end)
6524      (if (org-at-table-hline-p)
6525	  nil
6526	(org-table-goto-column col t)
6527	(and (looking-at "|[^|\n]+|")
6528	     (replace-match "|")))
6529      (beginning-of-line 2))
6530    (move-marker end nil)
6531    (goto-line linepos)
6532    (org-table-goto-column colpos)
6533    (org-table-align)
6534    (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
6535			    col -1 col)))
6536
6537(defun org-table-move-column-right ()
6538  "Move column to the right."
6539  (interactive)
6540  (org-table-move-column nil))
6541(defun org-table-move-column-left ()
6542  "Move column to the left."
6543  (interactive)
6544  (org-table-move-column 'left))
6545
6546(defun org-table-move-column (&optional left)
6547  "Move the current column to the right.  With arg LEFT, move to the left."
6548  (interactive "P")
6549  (if (not (org-at-table-p))
6550      (error "Not at a table"))
6551  (org-table-find-dataline)
6552  (org-table-check-inside-data-field)
6553  (let* ((col (org-table-current-column))
6554	 (col1 (if left (1- col) col))
6555	 (beg (org-table-begin))
6556	 (end (org-table-end))
6557	 ;; Current cursor position
6558	 (linepos (org-current-line))
6559	 (colpos (if left (1- col) (1+ col))))
6560    (if (and left (= col 1))
6561	(error "Cannot move column further left"))
6562    (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
6563	(error "Cannot move column further right"))
6564    (goto-char beg)
6565    (while (< (point) end)
6566      (if (org-at-table-hline-p)
6567	  nil
6568	(org-table-goto-column col1 t)
6569	(and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
6570	     (replace-match "|\\2|\\1|")))
6571      (beginning-of-line 2))
6572    (move-marker end nil)
6573    (goto-line linepos)
6574    (org-table-goto-column colpos)
6575    (org-table-align)
6576    (org-table-fix-formulas
6577     "$" (list (cons (number-to-string col) (number-to-string colpos))
6578	       (cons (number-to-string colpos) (number-to-string col))))))
6579
6580(defun org-table-move-row-down ()
6581  "Move table row down."
6582  (interactive)
6583  (org-table-move-row nil))
6584(defun org-table-move-row-up ()
6585  "Move table row up."
6586  (interactive)
6587  (org-table-move-row 'up))
6588
6589(defun org-table-move-row (&optional up)
6590  "Move the current table line down.  With arg UP, move it up."
6591  (interactive "P")
6592  (let* ((col (current-column))
6593	 (pos (point))
6594	 (hline1p (save-excursion (beginning-of-line 1)
6595				  (looking-at org-table-hline-regexp)))
6596	 (dline1 (org-table-current-dline))
6597	 (dline2 (+ dline1 (if up -1 1)))
6598	 (tonew (if up 0 2))
6599	 txt hline2p)
6600    (beginning-of-line tonew)
6601    (unless (org-at-table-p)
6602      (goto-char pos)
6603      (error "Cannot move row further"))
6604    (setq hline2p (looking-at org-table-hline-regexp))
6605    (goto-char pos)
6606    (beginning-of-line 1)
6607    (setq pos (point))
6608    (setq txt (buffer-substring (point) (1+ (point-at-eol))))
6609    (delete-region (point) (1+ (point-at-eol)))
6610    (beginning-of-line tonew)
6611    (insert txt)
6612    (beginning-of-line 0)
6613    (move-to-column col)
6614    (unless (or hline1p hline2p)
6615      (org-table-fix-formulas
6616       "@" (list (cons (number-to-string dline1) (number-to-string dline2))
6617		 (cons (number-to-string dline2) (number-to-string dline1)))))))
6618
6619(defun org-table-insert-row (&optional arg)
6620  "Insert a new row above the current line into the table.
6621With prefix ARG, insert below the current line."
6622  (interactive "P")
6623  (if (not (org-at-table-p))
6624      (error "Not at a table"))
6625  (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
6626	 (new (org-table-clean-line line)))
6627    ;; Fix the first field if necessary
6628    (if (string-match "^[ \t]*| *[#$] *|" line)
6629	(setq new (replace-match (match-string 0 line) t t new)))
6630    (beginning-of-line (if arg 2 1))
6631    (let (org-table-may-need-update) (insert-before-markers new "\n"))
6632    (beginning-of-line 0)
6633    (re-search-forward "| ?" (point-at-eol) t)
6634    (and (or org-table-may-need-update org-table-overlay-coordinates)
6635	 (org-table-align))
6636    (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
6637
6638(defun org-table-insert-hline (&optional arg)
6639  "Insert a horizontal-line below the current line into the table.
6640With prefix ARG, insert above the current line."
6641  (interactive "P")
6642  (if (not (org-at-table-p))
6643      (error "Not at a table"))
6644  (let ((line (org-table-clean-line
6645	       (buffer-substring (point-at-bol) (point-at-eol))))
6646	(col (current-column)))
6647    (while (string-match "|\\( +\\)|" line)
6648      (setq line (replace-match
6649		  (concat "+" (make-string (- (match-end 1) (match-beginning 1))
6650					   ?-) "|") t t line)))
6651    (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
6652    (beginning-of-line (if arg 1 2))
6653    (insert line "\n")
6654    (beginning-of-line (if arg 1 -1))
6655    (move-to-column col)
6656    (and org-table-overlay-coordinates (org-table-align))))
6657
6658(defun org-table-clean-line (s)
6659  "Convert a table line S into a string with only \"|\" and space.
6660In particular, this does handle wide and invisible characters."
6661  (if (string-match "^[ \t]*|-" s)
6662      ;; It's a hline, just map the characters
6663      (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
6664    (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
6665      (setq s (replace-match
6666	       (concat "|" (make-string (org-string-width (match-string 1 s))
6667					?\ ) "|")
6668	       t t s)))
6669    s))
6670
6671(defun org-table-kill-row ()
6672  "Delete the current row or horizontal line from the table."
6673  (interactive)
6674  (if (not (org-at-table-p))
6675      (error "Not at a table"))
6676  (let ((col (current-column))
6677	(dline (org-table-current-dline)))
6678    (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
6679    (if (not (org-at-table-p)) (beginning-of-line 0))
6680    (move-to-column col)
6681    (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
6682			    dline -1 dline)))
6683
6684
6685(defun org-table-sort-lines (with-case &optional sorting-type)
6686  "Sort table lines according to the column at point.
6687
6688The position of point indicates the column to be used for
6689sorting, and the range of lines is the range between the nearest
6690horizontal separator lines, or the entire table of no such lines
6691exist.  If point is before the first column, you will be prompted
6692for the sorting column.  If there is an active region, the mark
6693specifies the first line and the sorting column, while point
6694should be in the last line to be included into the sorting.
6695
6696The command then prompts for the sorting type which can be
6697alphabetically, numerically, or by time (as given in a time stamp
6698in the field).  Sorting in reverse order is also possible.
6699
6700With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
6701
6702If SORTING-TYPE is specified when this function is called from a Lisp
6703program, no prompting will take place.  SORTING-TYPE must be a character,
6704any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
6705should be done in reverse order."
6706  (interactive "P")
6707  (let* ((thisline (org-current-line))
6708	 (thiscol (org-table-current-column))
6709	 beg end bcol ecol tend tbeg column lns pos)
6710    (when (equal thiscol 0)
6711      (if (interactive-p)
6712	  (setq thiscol
6713		(string-to-number
6714		 (read-string "Use column N for sorting: ")))
6715	(setq thiscol 1))
6716      (org-table-goto-column thiscol))
6717    (org-table-check-inside-data-field)
6718    (if (org-region-active-p)
6719	(progn
6720	  (setq beg (region-beginning) end (region-end))
6721	  (goto-char beg)
6722	  (setq column (org-table-current-column)
6723		beg (point-at-bol))
6724	  (goto-char end)
6725	  (setq end (point-at-bol 2)))
6726      (setq column (org-table-current-column)
6727	    pos (point)
6728	    tbeg (org-table-begin)
6729	    tend (org-table-end))
6730      (if (re-search-backward org-table-hline-regexp tbeg t)
6731	  (setq beg (point-at-bol 2))
6732	(goto-char tbeg)
6733	(setq beg (point-at-bol 1)))
6734      (goto-char pos)
6735      (if (re-search-forward org-table-hline-regexp tend t)
6736	  (setq beg (point-at-bol 0))
6737	(goto-char tend)
6738	(setq end (point-at-bol))))
6739    (setq beg (move-marker (make-marker) beg)
6740	  end (move-marker (make-marker) end))
6741    (untabify beg end)
6742    (goto-char beg)
6743    (org-table-goto-column column)
6744    (skip-chars-backward "^|")
6745    (setq bcol (current-column))
6746    (org-table-goto-column (1+ column))
6747    (skip-chars-backward "^|")
6748    (setq ecol (1- (current-column)))
6749    (org-table-goto-column column)
6750    (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
6751		      (org-split-string (buffer-substring beg end) "\n")))
6752    (setq lns (org-do-sort lns "Table" with-case sorting-type))
6753    (delete-region beg end)
6754    (move-marker beg nil)
6755    (move-marker end nil)
6756    (insert (mapconcat 'cdr lns "\n") "\n")
6757    (goto-line thisline)
6758    (org-table-goto-column thiscol)
6759    (message "%d lines sorted, based on column %d" (length lns) column)))
6760
6761(defun org-table-cut-region (beg end)
6762  "Copy region in table to the clipboard and blank all relevant fields."
6763  (interactive "r")
6764  (org-table-copy-region beg end 'cut))
6765
6766(defun org-table-copy-region (beg end &optional cut)
6767  "Copy rectangular region in table to clipboard.
6768A special clipboard is used which can only be accessed
6769with `org-table-paste-rectangle'."
6770  (interactive "rP")
6771  (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
6772	 region cols
6773	 (rpl (if cut "  " nil)))
6774    (goto-char beg)
6775    (org-table-check-inside-data-field)
6776    (setq l01 (org-current-line)
6777	  c01 (org-table-current-column))
6778    (goto-char end)
6779    (org-table-check-inside-data-field)
6780    (setq l02 (org-current-line)
6781	  c02 (org-table-current-column))
6782    (setq l1 (min l01 l02) l2 (max l01 l02)
6783	  c1 (min c01 c02) c2 (max c01 c02))
6784    (catch 'exit
6785      (while t
6786	(catch 'nextline
6787	  (if (> l1 l2) (throw 'exit t))
6788	  (goto-line l1)
6789	  (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
6790	  (setq cols nil ic1 c1 ic2 c2)
6791	  (while (< ic1 (1+ ic2))
6792	    (push (org-table-get-field ic1 rpl) cols)
6793	    (setq ic1 (1+ ic1)))
6794	  (push (nreverse cols) region)
6795	  (setq l1 (1+ l1)))))
6796    (setq org-table-clip (nreverse region))
6797    (if cut (org-table-align))
6798    org-table-clip))
6799
6800(defun org-table-paste-rectangle ()
6801  "Paste a rectangular region into a table.
6802The upper right corner ends up in the current field.  All involved fields
6803will be overwritten.  If the rectangle does not fit into the present table,
6804the table is enlarged as needed.  The process ignores horizontal separator
6805lines."
6806  (interactive)
6807  (unless (and org-table-clip (listp org-table-clip))
6808    (error "First cut/copy a region to paste!"))
6809  (org-table-check-inside-data-field)
6810  (let* ((clip org-table-clip)
6811	 (line (org-current-line))
6812	 (col (org-table-current-column))
6813	 (org-enable-table-editor t)
6814	 (org-table-automatic-realign nil)
6815	 c cols field)
6816    (while (setq cols (pop clip))
6817      (while (org-at-table-hline-p) (beginning-of-line 2))
6818      (if (not (org-at-table-p))
6819	  (progn (end-of-line 0) (org-table-next-field)))
6820      (setq c col)
6821      (while (setq field (pop cols))
6822	(org-table-goto-column c nil 'force)
6823	(org-table-get-field nil field)
6824	(setq c (1+ c)))
6825      (beginning-of-line 2))
6826    (goto-line line)
6827    (org-table-goto-column col)
6828    (org-table-align)))
6829
6830(defun org-table-convert ()
6831  "Convert from `org-mode' table to table.el and back.
6832Obviously, this only works within limits.  When an Org-mode table is
6833converted to table.el, all horizontal separator lines get lost, because
6834table.el uses these as cell boundaries and has no notion of horizontal lines.
6835A table.el table can be converted to an Org-mode table only if it does not
6836do row or column spanning.  Multiline cells will become multiple cells.
6837Beware, Org-mode does not test if the table can be successfully converted - it
6838blindly applies a recipe that works for simple tables."
6839  (interactive)
6840  (require 'table)
6841  (if (org-at-table.el-p)
6842      ;; convert to Org-mode table
6843      (let ((beg (move-marker (make-marker) (org-table-begin t)))
6844	    (end (move-marker (make-marker) (org-table-end t))))
6845	(table-unrecognize-region beg end)
6846	(goto-char beg)
6847	(while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
6848	  (replace-match ""))
6849	(goto-char beg))
6850    (if (org-at-table-p)
6851	;; convert to table.el table
6852	(let ((beg (move-marker (make-marker) (org-table-begin)))
6853	      (end (move-marker (make-marker) (org-table-end))))
6854	  ;; first, get rid of all horizontal lines
6855	  (goto-char beg)
6856	  (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
6857	    (replace-match ""))
6858	  ;; insert a hline before first
6859	  (goto-char beg)
6860	  (org-table-insert-hline 'above)
6861	  (beginning-of-line -1)
6862	  ;; insert a hline after each line
6863	  (while (progn (beginning-of-line 3) (< (point) end))
6864	    (org-table-insert-hline))
6865	  (goto-char beg)
6866	  (setq end (move-marker end (org-table-end)))
6867	  ;; replace "+" at beginning and ending of hlines
6868	  (while (re-search-forward "^\\([ \t]*\\)|-" end t)
6869	    (replace-match "\\1+-"))
6870	  (goto-char beg)
6871	  (while (re-search-forward "-|[ \t]*$" end t)
6872	    (replace-match "-+"))
6873	  (goto-char beg)))))
6874
6875(defun org-table-wrap-region (arg)
6876  "Wrap several fields in a column like a paragraph.
6877This is useful if you'd like to spread the contents of a field over several
6878lines, in order to keep the table compact.
6879
6880If there is an active region, and both point and mark are in the same column,
6881the text in the column is wrapped to minimum width for the given number of
6882lines.  Generally, this makes the table more compact.  A prefix ARG may be
6883used to change the number of desired lines.  For example, `C-2 \\[org-table-wrap]'
6884formats the selected text to two lines.  If the region was longer than two
6885lines, the remaining lines remain empty.  A negative prefix argument reduces
6886the current number of lines by that amount.  The wrapped text is pasted back
6887into the table.  If you formatted it to more lines than it was before, fields
6888further down in the table get overwritten - so you might need to make space in
6889the table first.
6890
6891If there is no region, the current field is split at the cursor position and
6892the text fragment to the right of the cursor is prepended to the field one
6893line down.
6894
6895If there is no region, but you specify a prefix ARG, the current field gets
6896blank, and the content is appended to the field above."
6897  (interactive "P")
6898  (org-table-check-inside-data-field)
6899  (if (org-region-active-p)
6900      ;; There is a region:  fill as a paragraph
6901      (let* ((beg (region-beginning))
6902	     (cline (save-excursion (goto-char beg) (org-current-line)))
6903	     (ccol (save-excursion (goto-char beg) (org-table-current-column)))
6904	     nlines)
6905	(org-table-cut-region (region-beginning) (region-end))
6906	(if (> (length (car org-table-clip)) 1)
6907	    (error "Region must be limited to single column"))
6908	(setq nlines (if arg
6909			 (if (< arg 1)
6910			     (+ (length org-table-clip) arg)
6911			   arg)
6912		       (length org-table-clip)))
6913	(setq org-table-clip
6914	      (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
6915				      nil nlines)))
6916	(goto-line cline)
6917	(org-table-goto-column ccol)
6918	(org-table-paste-rectangle))
6919    ;; No region, split the current field at point
6920    (if arg
6921	;; combine with field above
6922	(let ((s (org-table-blank-field))
6923	      (col (org-table-current-column)))
6924	  (beginning-of-line 0)
6925	  (while (org-at-table-hline-p) (beginning-of-line 0))
6926	  (org-table-goto-column col)
6927	  (skip-chars-forward "^|")
6928	  (skip-chars-backward " ")
6929	  (insert " " (org-trim s))
6930	  (org-table-align))
6931      ;;  split field
6932      (when (looking-at "\\([^|]+\\)+|")
6933	(let ((s (match-string 1)))
6934	  (replace-match " |")
6935	  (goto-char (match-beginning 0))
6936	  (org-table-next-row)
6937	  (insert (org-trim s) " ")
6938	  (org-table-align))))))
6939
6940(defvar org-field-marker nil)
6941
6942(defun org-table-edit-field (arg)
6943  "Edit table field in a different window.
6944This is mainly useful for fields that contain hidden parts.
6945When called with a \\[universal-argument] prefix, just make the full field visible so that
6946it can be edited in place."
6947  (interactive "P")
6948  (if arg
6949      (let ((b (save-excursion (skip-chars-backward "^|") (point)))
6950	    (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
6951	(remove-text-properties b e '(org-cwidth t invisible t
6952						 display t intangible t))
6953	(if (and (boundp 'font-lock-mode) font-lock-mode)
6954	    (font-lock-fontify-block)))
6955    (let ((pos (move-marker (make-marker) (point)))
6956	  (field (org-table-get-field))
6957	  (cw (current-window-configuration))
6958	  p)
6959      (switch-to-buffer-other-window "*Org tmp*")
6960      (erase-buffer)
6961      (insert "#\n# Edit field and finish with C-c C-c\n#\n")
6962      (org-mode)
6963      (goto-char (setq p (point-max)))
6964      (insert (org-trim field))
6965      (remove-text-properties p (point-max)
6966			      '(invisible t org-cwidth t display t
6967					  intangible t))
6968      (goto-char p)
6969      (org-set-local 'org-finish-function
6970		     'org-table-finish-edit-field)
6971      (org-set-local 'org-window-configuration cw)
6972      (org-set-local 'org-field-marker pos)
6973      (message "Edit and finish with C-c C-c"))))
6974
6975(defun org-table-finish-edit-field ()
6976  "Finish editing a table data field.
6977Remove all newline characters, insert the result into the table, realign
6978the table and kill the editing buffer."
6979  (let ((pos org-field-marker)
6980	(cw org-window-configuration)
6981	(cb (current-buffer))
6982	text)
6983    (goto-char (point-min))
6984    (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
6985    (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
6986      (replace-match " "))
6987    (setq text (org-trim (buffer-string)))
6988    (set-window-configuration cw)
6989    (kill-buffer cb)
6990    (select-window (get-buffer-window (marker-buffer pos)))
6991    (goto-char pos)
6992    (move-marker pos nil)
6993    (org-table-check-inside-data-field)
6994    (org-table-get-field nil text)
6995    (org-table-align)
6996    (message "New field value inserted")))
6997
6998(defun org-trim (s)
6999  "Remove whitespace at beginning and end of string."
7000  (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
7001  (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
7002  s)
7003
7004(defun org-wrap (string &optional width lines)
7005  "Wrap string to either a number of lines, or a width in characters.
7006If WIDTH is non-nil, the string is wrapped to that width, however many lines
7007that costs.  If there is a word longer than WIDTH, the text is actually
7008wrapped to the length of that word.
7009IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
7010many lines, whatever width that takes.
7011The return value is a list of lines, without newlines at the end."
7012  (let* ((words (org-split-string string "[ \t\n]+"))
7013	 (maxword (apply 'max (mapcar 'org-string-width words)))
7014	 w ll)
7015    (cond (width
7016	   (org-do-wrap words (max maxword width)))
7017	  (lines
7018	   (setq w maxword)
7019	   (setq ll (org-do-wrap words maxword))
7020	   (if (<= (length ll) lines)
7021	       ll
7022	     (setq ll words)
7023	     (while (> (length ll) lines)
7024	       (setq w (1+ w))
7025	       (setq ll (org-do-wrap words w)))
7026	     ll))
7027	  (t (error "Cannot wrap this")))))
7028
7029
7030(defun org-do-wrap (words width)
7031  "Create lines of maximum width WIDTH (in characters) from word list WORDS."
7032  (let (lines line)
7033    (while words
7034      (setq line (pop words))
7035      (while (and words (< (+ (length line) (length (car words))) width))
7036	(setq line (concat line " " (pop words))))
7037      (setq lines (push line lines)))
7038    (nreverse lines)))
7039
7040(defun org-split-string (string &optional separators)
7041  "Splits STRING into substrings at SEPARATORS.
7042No empty strings are returned if there are matches at the beginning
7043and end of string."
7044  (let ((rexp (or separators "[ \f\t\n\r\v]+"))
7045	(start 0)
7046	notfirst
7047	(list nil))
7048    (while (and (string-match rexp string
7049			      (if (and notfirst
7050				       (= start (match-beginning 0))
7051				       (< start (length string)))
7052				  (1+ start) start))
7053		(< (match-beginning 0) (length string)))
7054      (setq notfirst t)
7055      (or (eq (match-beginning 0) 0)
7056	  (and (eq (match-beginning 0) (match-end 0))
7057	       (eq (match-beginning 0) start))
7058	  (setq list
7059		(cons (substring string start (match-beginning 0))
7060		      list)))
7061      (setq start (match-end 0)))
7062    (or (eq start (length string))
7063	(setq list
7064	      (cons (substring string start)
7065		    list)))
7066    (nreverse list)))
7067
7068(defun org-table-map-tables (function)
7069  "Apply FUNCTION to the start of all tables in the buffer."
7070  (save-excursion
7071    (save-restriction
7072      (widen)
7073      (goto-char (point-min))
7074      (while (re-search-forward org-table-any-line-regexp nil t)
7075	(message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
7076	(beginning-of-line 1)
7077	(if (looking-at org-table-line-regexp)
7078	    (save-excursion (funcall function)))
7079	(re-search-forward org-table-any-border-regexp nil 1))))
7080  (message "Mapping tables: done"))
7081
7082(defvar org-timecnt) ; dynamically scoped parameter
7083
7084(defun org-table-sum (&optional beg end nlast)
7085  "Sum numbers in region of current table column.
7086The result will be displayed in the echo area, and will be available
7087as kill to be inserted with \\[yank].
7088
7089If there is an active region, it is interpreted as a rectangle and all
7090numbers in that rectangle will be summed.  If there is no active
7091region and point is located in a table column, sum all numbers in that
7092column.
7093
7094If at least one number looks like a time HH:MM or HH:MM:SS, all other
7095numbers are assumed to be times as well (in decimal hours) and the
7096numbers are added as such.
7097
7098If NLAST is a number, only the NLAST fields will actually be summed."
7099  (interactive)
7100  (save-excursion
7101    (let (col (org-timecnt 0) diff h m s org-table-clip)
7102      (cond
7103       ((and beg end))   ; beg and end given explicitly
7104       ((org-region-active-p)
7105	(setq beg (region-beginning) end (region-end)))
7106       (t
7107	(setq col (org-table-current-column))
7108	(goto-char (org-table-begin))
7109	(unless (re-search-forward "^[ \t]*|[^-]" nil t)
7110	  (error "No table data"))
7111	(org-table-goto-column col)
7112	(setq beg (point))
7113	(goto-char (org-table-end))
7114	(unless (re-search-backward "^[ \t]*|[^-]" nil t)
7115	  (error "No table data"))
7116	(org-table-goto-column col)
7117	(setq end (point))))
7118      (let* ((items (apply 'append (org-table-copy-region beg end)))
7119	     (items1 (cond ((not nlast) items)
7120			   ((>= nlast (length items)) items)
7121			   (t (setq items (reverse items))
7122			      (setcdr (nthcdr (1- nlast) items) nil)
7123			      (nreverse items))))
7124	     (numbers (delq nil (mapcar 'org-table-get-number-for-summing
7125					items1)))
7126	     (res (apply '+ numbers))
7127	     (sres (if (= org-timecnt 0)
7128		       (format "%g" res)
7129		     (setq diff (* 3600 res)
7130			   h (floor (/ diff 3600)) diff (mod diff 3600)
7131			   m (floor (/ diff 60)) diff (mod diff 60)
7132			   s diff)
7133		     (format "%d:%02d:%02d" h m s))))
7134	(kill-new sres)
7135	(if (interactive-p)
7136	    (message "%s"
7137		     (substitute-command-keys
7138		      (format "Sum of %d items: %-20s     (\\[yank] will insert result into buffer)"
7139			      (length numbers) sres))))
7140	sres))))
7141
7142(defun org-table-get-number-for-summing (s)
7143  (let (n)
7144    (if (string-match "^ *|? *" s)
7145	(setq s (replace-match "" nil nil s)))
7146    (if (string-match " *|? *$" s)
7147	(setq s (replace-match "" nil nil s)))
7148    (setq n (string-to-number s))
7149    (cond
7150     ((and (string-match "0" s)
7151	   (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
7152     ((string-match "\\`[ \t]+\\'" s)         nil)
7153     ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
7154      (let ((h (string-to-number (or (match-string 1 s) "0")))
7155	    (m (string-to-number (or (match-string 2 s) "0")))
7156	    (s (string-to-number (or (match-string 4 s) "0"))))
7157	(if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
7158	(* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
7159     ((equal n 0)                             nil)
7160     (t n))))
7161
7162(defun org-table-current-field-formula ()
7163  "Return the formula active for the current field.
7164Assumes that specials are in place."
7165  (let* ((name (car (rassoc (list (org-current-line)
7166				  (org-table-current-column))
7167			    org-table-named-field-locations)))
7168	 (col (org-table-current-column))
7169	 (scol (int-to-string col))
7170	 (ref (format "@%d$%d" (org-table-current-dline) col))
7171	 (stored-list (org-table-get-stored-formulas))
7172	 (ass (or (assoc name stored-list)
7173		  (assoc ref stored-list)
7174		  (assoc scol stored-list))))
7175    (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
7176		    (cdr ass)))))
7177
7178(defun org-table-get-formula (&optional equation named)
7179  "Read a formula from the minibuffer, offer stored formula as default.
7180When NAMED is non-nil, look for a named equation."
7181  (let* ((stored-list (org-table-get-stored-formulas))
7182	 (name (car (rassoc (list (org-current-line)
7183				  (org-table-current-column))
7184			    org-table-named-field-locations)))
7185	 (ref (format "@%d$%d" (org-table-current-dline)
7186		      (org-table-current-column)))
7187	 (refass (assoc ref stored-list))
7188	 (scol (if named
7189		   (if name name ref)
7190		 (int-to-string (org-table-current-column))))
7191	 (dummy (and (or name refass) (not named)
7192		     (not (y-or-n-p "Replace field formula with column formula? " ))
7193		     (error "Abort")))
7194	 (name (or name ref))
7195	 (org-table-may-need-update nil)
7196	 (stored (cdr (assoc scol stored-list)))
7197	 (eq (cond
7198	      ((and stored equation (string-match "^ *=? *$" equation))
7199	       stored)
7200	      ((stringp equation)
7201	       equation)
7202	      (t (read-string
7203		  (format "%s formula $%s=" (if named "Field" "Column") scol)
7204		  (or stored "") 'org-table-formula-history
7205		  ;stored
7206		  ))))
7207	 mustsave)
7208    (when (not (string-match "\\S-" eq))
7209      ;; remove formula
7210      (setq stored-list (delq (assoc scol stored-list) stored-list))
7211      (org-table-store-formulas stored-list)
7212      (error "Formula removed"))
7213    (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
7214    (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
7215    (if (and name (not named))
7216	;; We set the column equation, delete the named one.
7217	(setq stored-list (delq (assoc name stored-list) stored-list)
7218	      mustsave t))
7219    (if stored
7220	(setcdr (assoc scol stored-list) eq)
7221      (setq stored-list (cons (cons scol eq) stored-list)))
7222    (if (or mustsave (not (equal stored eq)))
7223	(org-table-store-formulas stored-list))
7224    eq))
7225
7226(defun org-table-store-formulas (alist)
7227  "Store the list of formulas below the current table."
7228  (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
7229  (save-excursion
7230    (goto-char (org-table-end))
7231    (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
7232	(progn
7233	  ;; don't overwrite TBLFM, we might use text properties to store stuff
7234	  (goto-char (match-beginning 2))
7235	  (delete-region (match-beginning 2) (match-end 0)))
7236      (insert "#+TBLFM:"))
7237    (insert " "
7238	    (mapconcat (lambda (x)
7239			 (concat
7240			  (if (equal (string-to-char (car x)) ?@) "" "$")
7241			  (car x) "=" (cdr x)))
7242		       alist "::")
7243	    "\n")))
7244
7245(defun org-table-get-stored-formulas ()
7246  "Return an alist with the stored formulas directly after current table."
7247  (interactive)
7248  (let (scol eq eq-alist strings string seen)
7249    (save-excursion
7250      (goto-char (org-table-end))
7251      (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
7252	(setq strings (org-split-string (match-string 2) " *:: *"))
7253	(while (setq string (pop strings))
7254	  (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
7255	    (setq scol (if (match-end 2)
7256			   (match-string 2 string)
7257			 (match-string 1 string))
7258		  eq (match-string 3 string)
7259		  eq-alist (cons (cons scol eq) eq-alist))
7260	    (if (member scol seen)
7261		(error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
7262	      (push scol seen))))))
7263    (nreverse eq-alist)))
7264
7265(defun org-table-fix-formulas (key replace &optional limit delta remove)
7266  "Modify the equations after the table structure has been edited.
7267KEY is \"@\" or \"$\".  REPLACE is an alist of numbers to replace.
7268For all numbers larger than LIMIT, shift them by DELTA."
7269  (save-excursion
7270    (goto-char (org-table-end))
7271    (when (looking-at "#\\+TBLFM:")
7272      (let ((re (concat key "\\([0-9]+\\)"))
7273	    (re2
7274	     (when remove
7275	       (if (equal key "$")
7276		   (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
7277		 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
7278	    s n a)
7279	(when remove
7280	  (while (re-search-forward re2 (point-at-eol) t)
7281	    (replace-match "")))
7282	(while (re-search-forward re (point-at-eol) t)
7283	  (setq s (match-string 1) n (string-to-number s))
7284	  (cond
7285	   ((setq a (assoc s replace))
7286	    (replace-match (concat key (cdr a)) t t))
7287	   ((and limit (> n limit))
7288	    (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
7289
7290(defun org-table-get-specials ()
7291  "Get the column names and local parameters for this table."
7292  (save-excursion
7293    (let ((beg (org-table-begin)) (end (org-table-end))
7294	  names name fields fields1 field cnt
7295	  c v l line col types dlines hlines)
7296      (setq org-table-column-names nil
7297	    org-table-local-parameters nil
7298	    org-table-named-field-locations nil
7299	    org-table-current-begin-line nil
7300	    org-table-current-line-types nil)
7301      (goto-char beg)
7302      (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
7303	(setq names (org-split-string (match-string 1) " *| *")
7304	      cnt 1)
7305	(while (setq name (pop names))
7306	  (setq cnt (1+ cnt))
7307	  (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
7308	      (push (cons name (int-to-string cnt)) org-table-column-names))))
7309      (setq org-table-column-names (nreverse org-table-column-names))
7310      (setq org-table-column-name-regexp
7311	    (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
7312      (goto-char beg)
7313      (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
7314	(setq fields (org-split-string (match-string 1) " *| *"))
7315	(while (setq field (pop fields))
7316	  (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
7317	      (push (cons (match-string 1 field) (match-string 2 field))
7318		    org-table-local-parameters))))
7319      (goto-char beg)
7320      (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
7321	(setq c (match-string 1)
7322	      fields (org-split-string (match-string 2) " *| *"))
7323	(save-excursion
7324	  (beginning-of-line (if (equal c "_") 2 0))
7325	  (setq line (org-current-line) col 1)
7326	  (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
7327	       (setq fields1 (org-split-string (match-string 1) " *| *"))))
7328	(while (and fields1 (setq field (pop fields)))
7329	  (setq v (pop fields1) col (1+ col))
7330	  (when (and (stringp field) (stringp v)
7331		     (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
7332	      (push (cons field v) org-table-local-parameters)
7333	      (push (list field line col) org-table-named-field-locations))))
7334      ;; Analyse the line types
7335      (goto-char beg)
7336      (setq org-table-current-begin-line (org-current-line)
7337	    l org-table-current-begin-line)
7338      (while (looking-at "[ \t]*|\\(-\\)?")
7339	(push (if (match-end 1) 'hline 'dline) types)
7340	(if (match-end 1) (push l hlines) (push l dlines))
7341	(beginning-of-line 2)
7342	(setq l (1+ l)))
7343      (setq org-table-current-line-types (apply 'vector (nreverse types))
7344	    org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
7345	    org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
7346
7347(defun org-this-word ()
7348  ;; Get the current word
7349  (save-excursion
7350    (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
7351	  (end (progn (skip-chars-forward "^ \t\n") (point))))
7352      (buffer-substring-no-properties beg end))))
7353
7354(defun org-table-maybe-eval-formula ()
7355  "Check if the current field starts with \"=\" or \":=\".
7356If yes, store the formula and apply it."
7357  ;; We already know we are in a table.  Get field will only return a formula
7358  ;; when appropriate.  It might return a separator line, but no problem.
7359  (when org-table-formula-evaluate-inline
7360    (let* ((field (org-trim (or (org-table-get-field) "")))
7361	   named eq)
7362      (when (string-match "^:?=\\(.*\\)" field)
7363	(setq named (equal (string-to-char field) ?:)
7364	      eq (match-string 1 field))
7365	(if (or (fboundp 'calc-eval)
7366		(equal (substring eq 0 (min 2 (length eq))) "'("))
7367	    (org-table-eval-formula (if named '(4) nil) eq)
7368	  (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
7369
7370(defvar org-recalc-commands nil
7371  "List of commands triggering the recalculation of a line.
7372Will be filled automatically during use.")
7373
7374(defvar org-recalc-marks
7375  '((" " . "Unmarked: no special line, no automatic recalculation")
7376    ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
7377    ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
7378    ("!" . "Column name definition line. Reference in formula as $name.")
7379    ("$" . "Parameter definition line name=value. Reference in formula as $name.")
7380    ("_" . "Names for values in row below this one.")
7381    ("^" . "Names for values in row above this one.")))
7382
7383(defun org-table-rotate-recalc-marks (&optional newchar)
7384  "Rotate the recalculation mark in the first column.
7385If in any row, the first field is not consistent with a mark,
7386insert a new column for the markers.
7387When there is an active region, change all the lines in the region,
7388after prompting for the marking character.
7389After each change, a message will be displayed indicating the meaning
7390of the new mark."
7391  (interactive)
7392  (unless (org-at-table-p) (error "Not at a table"))
7393  (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
7394	 (beg (org-table-begin))
7395	 (end (org-table-end))
7396	 (l (org-current-line))
7397	 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
7398	 (l2 (if (org-region-active-p) (org-current-line (region-end))))
7399	 (have-col
7400	  (save-excursion
7401	    (goto-char beg)
7402	    (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
7403	 (col (org-table-current-column))
7404	 (forcenew (car (assoc newchar org-recalc-marks)))
7405	 epos new)
7406    (when l1
7407      (message "Change region to what mark?  Type # * ! $ or SPC: ")
7408      (setq newchar (char-to-string (read-char-exclusive))
7409	    forcenew (car (assoc newchar org-recalc-marks))))
7410    (if (and newchar (not forcenew))
7411	(error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
7412	       newchar))
7413    (if l1 (goto-line l1))
7414    (save-excursion
7415      (beginning-of-line 1)
7416      (unless (looking-at org-table-dataline-regexp)
7417	(error "Not at a table data line")))
7418    (unless have-col
7419      (org-table-goto-column 1)
7420      (org-table-insert-column)
7421      (org-table-goto-column (1+ col)))
7422    (setq epos (point-at-eol))
7423    (save-excursion
7424      (beginning-of-line 1)
7425      (org-table-get-field
7426       1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
7427	     (concat " "
7428		     (setq new (or forcenew
7429				   (cadr (member (match-string 1) marks))))
7430		     " ")
7431	   " # ")))
7432    (if (and l1 l2)
7433	(progn
7434	  (goto-line l1)
7435	  (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
7436	    (and (looking-at org-table-dataline-regexp)
7437		 (org-table-get-field 1 (concat " " new " "))))
7438	  (goto-line l1)))
7439    (if (not (= epos (point-at-eol))) (org-table-align))
7440    (goto-line l)
7441    (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
7442
7443(defun org-table-maybe-recalculate-line ()
7444  "Recompute the current line if marked for it, and if we haven't just done it."
7445  (interactive)
7446  (and org-table-allow-automatic-line-recalculation
7447       (not (and (memq last-command org-recalc-commands)
7448		 (equal org-last-recalc-line (org-current-line))))
7449       (save-excursion (beginning-of-line 1)
7450		       (looking-at org-table-auto-recalculate-regexp))
7451       (org-table-recalculate) t))
7452
7453(defvar org-table-formula-debug nil
7454  "Non-nil means, debug table formulas.
7455When nil, simply write \"#ERROR\" in corrupted fields.")
7456(make-variable-buffer-local 'org-table-formula-debug)
7457
7458(defvar modes)
7459(defsubst org-set-calc-mode (var &optional value)
7460  (if (stringp var)
7461      (setq var (assoc var '(("D" calc-angle-mode deg)
7462			     ("R" calc-angle-mode rad)
7463			     ("F" calc-prefer-frac t)
7464			     ("S" calc-symbolic-mode t)))
7465	    value (nth 2 var) var (nth 1 var)))
7466  (if (memq var modes)
7467      (setcar (cdr (memq var modes)) value)
7468    (cons var (cons value modes)))
7469  modes)
7470
7471(defun org-table-eval-formula (&optional arg equation
7472					 suppress-align suppress-const
7473					 suppress-store suppress-analysis)
7474  "Replace the table field value at the cursor by the result of a calculation.
7475
7476This function makes use of Dave Gillespie's Calc package, in my view the
7477most exciting program ever written for GNU Emacs.  So you need to have Calc
7478installed in order to use this function.
7479
7480In a table, this command replaces the value in the current field with the
7481result of a formula.  It also installs the formula as the \"current\" column
7482formula, by storing it in a special line below the table.  When called
7483with a `C-u' prefix, the current field must ba a named field, and the
7484formula is installed as valid in only this specific field.
7485
7486When called with two `C-u' prefixes, insert the active equation
7487for the field back into the current field, so that it can be
7488edited there.  This is useful in order to use \\[org-show-reference]
7489to check the referenced fields.
7490
7491When called, the command first prompts for a formula, which is read in
7492the minibuffer.  Previously entered formulas are available through the
7493history list, and the last used formula is offered as a default.
7494These stored formulas are adapted correctly when moving, inserting, or
7495deleting columns with the corresponding commands.
7496
7497The formula can be any algebraic expression understood by the Calc package.
7498For details, see the Org-mode manual.
7499
7500This function can also be called from Lisp programs and offers
7501additional arguments: EQUATION can be the formula to apply.  If this
7502argument is given, the user will not be prompted.  SUPPRESS-ALIGN is
7503used to speed-up recursive calls by by-passing unnecessary aligns.
7504SUPPRESS-CONST suppresses the interpretation of constants in the
7505formula, assuming that this has been done already outside the function.
7506SUPPRESS-STORE means the formula should not be stored, either because
7507it is already stored, or because it is a modified equation that should
7508not overwrite the stored one."
7509  (interactive "P")
7510  (org-table-check-inside-data-field)
7511  (or suppress-analysis (org-table-get-specials))
7512  (if (equal arg '(16))
7513      (let ((eq (org-table-current-field-formula)))
7514	(or eq (error "No equation active for current field"))
7515	(org-table-get-field nil eq)
7516	(org-table-align)
7517	(setq org-table-may-need-update t))
7518    (let* (fields
7519	   (ndown (if (integerp arg) arg 1))
7520	   (org-table-automatic-realign nil)
7521	   (case-fold-search nil)
7522	   (down (> ndown 1))
7523	   (formula (if (and equation suppress-store)
7524			equation
7525		      (org-table-get-formula equation (equal arg '(4)))))
7526	   (n0 (org-table-current-column))
7527	   (modes (copy-sequence org-calc-default-modes))
7528	   (numbers nil) ; was a variable, now fixed default
7529	   (keep-empty nil)
7530	   n form form0 bw fmt x ev orig c lispp)
7531      ;; Parse the format string.  Since we have a lot of modes, this is
7532      ;; a lot of work.  However, I think calc still uses most of the time.
7533      (if (string-match ";" formula)
7534	  (let ((tmp (org-split-string formula ";")))
7535	    (setq formula (car tmp)
7536		  fmt (concat (cdr (assoc "%" org-table-local-parameters))
7537			      (nth 1 tmp)))
7538	    (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
7539	      (setq c (string-to-char (match-string 1 fmt))
7540		    n (string-to-number (match-string 2 fmt)))
7541	      (if (= c ?p)
7542		  (setq modes (org-set-calc-mode 'calc-internal-prec n))
7543		(setq modes (org-set-calc-mode
7544			     'calc-float-format
7545			     (list (cdr (assoc c '((?n . float) (?f . fix)
7546						   (?s . sci) (?e . eng))))
7547				   n))))
7548	      (setq fmt (replace-match "" t t fmt)))
7549	    (if (string-match "[NT]" fmt)
7550		(setq numbers (equal (match-string 0 fmt) "N")
7551		      fmt (replace-match "" t t fmt)))
7552	    (if (string-match "E" fmt)
7553		(setq keep-empty t
7554		      fmt (replace-match "" t t fmt)))
7555	    (while (string-match "[DRFS]" fmt)
7556	      (setq modes (org-set-calc-mode (match-string 0 fmt)))
7557	      (setq fmt (replace-match "" t t fmt)))
7558	    (unless (string-match "\\S-" fmt)
7559	      (setq fmt nil))))
7560      (if (and (not suppress-const) org-table-formula-use-constants)
7561	  (setq formula (org-table-formula-substitute-names formula)))
7562      (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
7563      (while (> ndown 0)
7564	(setq fields (org-split-string
7565		      (org-no-properties
7566		       (buffer-substring (point-at-bol) (point-at-eol)))
7567		      " *| *"))
7568	(if numbers
7569	    (setq fields (mapcar
7570			  (lambda (x) (number-to-string (string-to-number x)))
7571			  fields)))
7572	(setq ndown (1- ndown))
7573	(setq form (copy-sequence formula)
7574	      lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
7575	;; Check for old vertical references
7576	(setq form (org-rewrite-old-row-references form))
7577	;; Insert complex ranges
7578	(while (string-match org-table-range-regexp form)
7579	  (setq form
7580		(replace-match
7581		 (save-match-data
7582		   (org-table-make-reference
7583		    (org-table-get-range (match-string 0 form) nil n0)
7584		    keep-empty numbers lispp))
7585		 t t form)))
7586	;; Insert simple ranges
7587	(while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)"  form)
7588	  (setq form
7589		(replace-match
7590		 (save-match-data
7591		   (org-table-make-reference
7592		    (org-sublist
7593		     fields (string-to-number (match-string 1 form))
7594		     (string-to-number (match-string 2 form)))
7595		    keep-empty numbers lispp))
7596		 t t form)))
7597	(setq form0 form)
7598	;; Insert the references to fields in same row
7599	(while (string-match "\\$\\([0-9]+\\)?" form)
7600	  (setq n (if (match-beginning 1)
7601		      (string-to-number (match-string 1 form))
7602		    n0)
7603		x (nth (1- n) fields))
7604	  (unless x (error "Invalid field specifier \"%s\""
7605			   (match-string 0 form)))
7606	  (setq form (replace-match
7607		      (save-match-data
7608			(org-table-make-reference x nil numbers lispp))
7609		      t t form)))
7610	(if lispp
7611	    (setq ev (condition-case nil
7612			 (eval (eval (read form)))
7613		       (error "#ERROR"))
7614		  ev (if (numberp ev) (number-to-string ev) ev))
7615	  (or (fboundp 'calc-eval)
7616	      (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
7617	  (setq ev (calc-eval (cons form modes)
7618			      (if numbers 'num))))
7619
7620	(when org-table-formula-debug
7621	  (with-output-to-temp-buffer "*Substitution History*"
7622	    (princ (format "Substitution history of formula
7623Orig:   %s
7624$xyz->  %s
7625@r$c->  %s
7626$1->    %s\n" orig formula form0 form))
7627	    (if (listp ev)
7628		(princ (format "       %s^\nError:  %s"
7629			       (make-string (car ev) ?\-) (nth 1 ev)))
7630	      (princ (format "Result: %s\nFormat: %s\nFinal:  %s"
7631			     ev (or fmt "NONE")
7632			     (if fmt (format fmt (string-to-number ev)) ev)))))
7633	  (setq bw (get-buffer-window "*Substitution History*"))
7634	  (shrink-window-if-larger-than-buffer bw)
7635	  (unless (and (interactive-p) (not ndown))
7636	    (unless (let (inhibit-redisplay)
7637		      (y-or-n-p "Debugging Formula. Continue to next? "))
7638	      (org-table-align)
7639	      (error "Abort"))
7640	    (delete-window bw)
7641	    (message "")))
7642	(if (listp ev) (setq fmt nil ev "#ERROR"))
7643	(org-table-justify-field-maybe
7644	 (if fmt (format fmt (string-to-number ev)) ev))
7645	(if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
7646	    (call-interactively 'org-return)
7647	  (setq ndown 0)))
7648      (and down (org-table-maybe-recalculate-line))
7649      (or suppress-align (and org-table-may-need-update
7650			      (org-table-align))))))
7651
7652(defun org-table-get-range (desc &optional tbeg col highlight)
7653  "Get a calc vector from a column, accorting to descriptor DESC.
7654Optional arguments TBEG and COL can give the beginning of the table and
7655the current column, to avoid unnecessary parsing.
7656HIGHLIGHT means, just highlight the range."
7657  (if (not (equal (string-to-char desc) ?@))
7658      (setq desc (concat "@" desc)))
7659  (save-excursion
7660    (or tbeg (setq tbeg (org-table-begin)))
7661    (or col (setq col (org-table-current-column)))
7662    (let ((thisline (org-current-line))
7663	  beg end c1 c2 r1 r2 rangep tmp)
7664      (unless (string-match org-table-range-regexp desc)
7665	(error "Invalid table range specifier `%s'" desc))
7666      (setq rangep (match-end 3)
7667	    r1 (and (match-end 1) (match-string 1 desc))
7668	    r2 (and (match-end 4) (match-string 4 desc))
7669	    c1 (and (match-end 2) (substring (match-string 2 desc) 1))
7670	    c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
7671
7672      (and c1 (setq c1 (+ (string-to-number c1)
7673			  (if (memq (string-to-char c1) '(?- ?+)) col 0))))
7674      (and c2 (setq c2 (+ (string-to-number c2)
7675			  (if (memq (string-to-char c2) '(?- ?+)) col 0))))
7676      (if (equal r1 "") (setq r1 nil))
7677      (if (equal r2 "") (setq r2 nil))
7678      (if r1 (setq r1 (org-table-get-descriptor-line r1)))
7679      (if r2 (setq r2 (org-table-get-descriptor-line r2)))
7680;      (setq r2 (or r2 r1) c2 (or c2 c1))
7681      (if (not r1) (setq r1 thisline))
7682      (if (not r2) (setq r2 thisline))
7683      (if (not c1) (setq c1 col))
7684      (if (not c2) (setq c2 col))
7685      (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
7686	  ;; just one field
7687	  (progn
7688	    (goto-line r1)
7689	    (while (not (looking-at org-table-dataline-regexp))
7690	      (beginning-of-line 2))
7691	    (prog1 (org-table-get-field c1)
7692	      (if highlight (org-table-highlight-rectangle (point) (point)))))
7693	;; A range, return a vector
7694	;; First sort the numbers to get a regular ractangle
7695	(if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
7696	(if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
7697	(goto-line r1)
7698	(while (not (looking-at org-table-dataline-regexp))
7699	  (beginning-of-line 2))
7700	(org-table-goto-column c1)
7701	(setq beg (point))
7702	(goto-line r2)
7703	(while (not (looking-at org-table-dataline-regexp))
7704	  (beginning-of-line 0))
7705	(org-table-goto-column c2)
7706	(setq end (point))
7707	(if highlight
7708	    (org-table-highlight-rectangle
7709	     beg (progn (skip-chars-forward "^|\n") (point))))
7710	;; return string representation of calc vector
7711	(apply 'append (org-table-copy-region beg end))))))
7712
7713(defun org-table-get-descriptor-line (desc &optional cline bline table)
7714  "Analyze descriptor DESC and retrieve the corresponding line number.
7715The cursor is currently in line CLINE, the table begins in line BLINE,
7716and TABLE is a vector with line types."
7717  (if (string-match "^[0-9]+$" desc)
7718      (aref org-table-dlines (string-to-number desc))
7719    (setq cline (or cline (org-current-line))
7720	  bline (or bline org-table-current-begin-line)
7721	  table (or table org-table-current-line-types))
7722    (if (or
7723	 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
7724	 ;;                     1  2          3           4  5          6
7725	 (and (not (match-end 3)) (not (match-end 6)))
7726	 (and (match-end 3) (match-end 6) (not (match-end 5))))
7727	(error "invalid row descriptor `%s'" desc))
7728    (let* ((hdir (and (match-end 2) (match-string 2 desc)))
7729	   (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
7730	   (odir (and (match-end 5) (match-string 5 desc)))
7731	   (on (if (match-end 6) (string-to-number (match-string 6 desc))))
7732	   (i (- cline bline))
7733	   (rel (and (match-end 6)
7734		     (or (and (match-end 1) (not (match-end 3)))
7735			 (match-end 5)))))
7736      (if (and hn (not hdir))
7737	  (progn
7738	    (setq i 0 hdir "+")
7739	    (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
7740      (if (and (not hn) on (not odir))
7741	  (error "should never happen");;(aref org-table-dlines on) FIXME
7742	(if (and hn (> hn 0))
7743	    (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
7744	(if on
7745	    (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
7746	(+ bline i)))))
7747
7748(defun org-find-row-type (table i type backwards relative n)
7749  (let ((l (length table)))
7750    (while (> n 0)
7751      (while (and (setq i (+ i (if backwards -1 1)))
7752		  (>= i 0) (< i l)
7753		  (not (eq (aref table i) type))
7754		  (if (and relative (eq (aref table i) 'hline))
7755		      (progn (setq i (- i (if backwards -1 1)) n 1) nil)
7756		    t)))
7757      (setq n (1- n)))
7758    (if (or (< i 0) (>= i l))
7759	(error "Row descriptior leads outside table")
7760      i)))
7761
7762(defun org-rewrite-old-row-references (s)
7763  (if (string-match "&[-+0-9I]" s)
7764      (error "Formula contains old &row reference, please rewrite using @-syntax")
7765    s))
7766
7767(defun org-table-make-reference (elements keep-empty numbers lispp)
7768  "Convert list ELEMENTS to something appropriate to insert into formula.
7769KEEP-EMPTY indicated to keep empty fields, default is to skip them.
7770NUMBERS indicates that everything should be converted to numbers.
7771LISPP means to return something appropriate for a Lisp list."
7772  (if (stringp elements) ; just a single val
7773      (if lispp
7774	  (prin1-to-string (if numbers (string-to-number elements) elements))
7775	(if (equal elements "") (setq elements "0"))
7776	(if numbers (number-to-string (string-to-number elements)) elements))
7777    (unless keep-empty
7778      (setq elements
7779	    (delq nil
7780		  (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
7781			  elements))))
7782    (setq elements (or elements '("0")))
7783    (if lispp
7784	(mapconcat 'prin1-to-string
7785		   (if numbers (mapcar 'string-to-number elements) elements)
7786		   " ")
7787      (concat "[" (mapconcat
7788		   (lambda (x)
7789		     (if numbers (number-to-string (string-to-number x)) x))
7790		   elements
7791		   ",") "]"))))
7792
7793(defun org-table-recalculate (&optional all noalign)
7794  "Recalculate the current table line by applying all stored formulas.
7795With prefix arg ALL, do this for all lines in the table."
7796  (interactive "P")
7797  (or (memq this-command org-recalc-commands)
7798      (setq org-recalc-commands (cons this-command org-recalc-commands)))
7799  (unless (org-at-table-p) (error "Not at a table"))
7800  (if (equal all '(16))
7801      (org-table-iterate)
7802    (org-table-get-specials)
7803    (let* ((eqlist (sort (org-table-get-stored-formulas)
7804			 (lambda (a b) (string< (car a) (car b)))))
7805	   (inhibit-redisplay (not debug-on-error))
7806	   (line-re org-table-dataline-regexp)
7807	   (thisline (org-current-line))
7808	   (thiscol (org-table-current-column))
7809	   beg end entry eqlnum eqlname eql (cnt 0) eq a name)
7810      ;; Insert constants in all formulas
7811      (setq eqlist
7812	    (mapcar (lambda (x)
7813		      (setcdr x (org-table-formula-substitute-names (cdr x)))
7814		      x)
7815		    eqlist))
7816      ;; Split the equation list
7817      (while (setq eq (pop eqlist))
7818	(if (<= (string-to-char (car eq)) ?9)
7819	    (push eq eqlnum)
7820	  (push eq eqlname)))
7821      (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
7822      (if all
7823	  (progn
7824	    (setq end (move-marker (make-marker) (1+ (org-table-end))))
7825	    (goto-char (setq beg (org-table-begin)))
7826	    (if (re-search-forward org-table-calculate-mark-regexp end t)
7827		;; This is a table with marked lines, compute selected lines
7828		(setq line-re org-table-recalculate-regexp)
7829	      ;; Move forward to the first non-header line
7830	      (if (and (re-search-forward org-table-dataline-regexp end t)
7831		       (re-search-forward org-table-hline-regexp end t)
7832		       (re-search-forward org-table-dataline-regexp end t))
7833		  (setq beg (match-beginning 0))
7834		nil))) ;; just leave beg where it is
7835	(setq beg (point-at-bol)
7836	      end (move-marker (make-marker) (1+ (point-at-eol)))))
7837      (goto-char beg)
7838      (and all (message "Re-applying formulas to full table..."))
7839      (while (re-search-forward line-re end t)
7840	(unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
7841	  ;; Unprotected line, recalculate
7842	  (and all (message "Re-applying formulas to full table...(line %d)"
7843			    (setq cnt (1+ cnt))))
7844	  (setq org-last-recalc-line (org-current-line))
7845	  (setq eql eqlnum)
7846	  (while (setq entry (pop eql))
7847	    (goto-line org-last-recalc-line)
7848	    (org-table-goto-column (string-to-number (car entry)) nil 'force)
7849	    (org-table-eval-formula nil (cdr entry)
7850				    'noalign 'nocst 'nostore 'noanalysis))))
7851      (goto-line thisline)
7852      (org-table-goto-column thiscol)
7853      (or noalign (and org-table-may-need-update (org-table-align))
7854	  (and all (message "Re-applying formulas to %d lines...done" cnt)))
7855      ;; Now do the named fields
7856      (while (setq eq (pop eqlname))
7857	(setq name (car eq)
7858	      a (assoc name org-table-named-field-locations))
7859	(and (not a)
7860	     (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
7861	     (setq a
7862		   (list
7863		    name
7864		    (aref org-table-dlines
7865			  (string-to-number (match-string 1 name)))
7866		    (string-to-number (match-string 2 name)))))
7867	(when (and a (or all (equal (nth 1 a) thisline)))
7868	  (message "Re-applying formula to field: %s" name)
7869	  (goto-line (nth 1 a))
7870	  (org-table-goto-column (nth 2 a))
7871	  (org-table-eval-formula nil (cdr eq) 'noalign 'nocst
7872				  'nostore 'noanalysis)))
7873      ;; back to initial position
7874      (message "Re-applying formulas...done")
7875      (goto-line thisline)
7876      (org-table-goto-column thiscol)
7877      (or noalign (and org-table-may-need-update (org-table-align))
7878	  (and all (message "Re-applying formulas...done"))))))
7879
7880(defun org-table-iterate (&optional arg)
7881  "Recalculate the table until it does not change anymore."
7882  (interactive "P")
7883  (let ((imax (if arg (prefix-numeric-value arg) 10))
7884	(i 0)
7885	(lasttbl (buffer-substring (org-table-begin) (org-table-end)))
7886	thistbl)
7887    (catch 'exit
7888      (while (< i imax)
7889	(setq i (1+ i))
7890	(org-table-recalculate 'all)
7891	(setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
7892	(if (not (string= lasttbl thistbl))
7893	    (setq lasttbl thistbl)
7894	  (if (> i 1)
7895	      (message "Convergence after %d iterations" i)
7896	    (message "Table was already stable"))
7897	  (throw 'exit t)))
7898      (error "No convergence after %d iterations" i))))
7899
7900(defun org-table-formula-substitute-names (f)
7901  "Replace $const with values in string F."
7902  (let ((start 0) a (f1 f))
7903    ;; First, check for column names
7904    (while (setq start (string-match org-table-column-name-regexp f start))
7905      (setq start (1+ start))
7906      (setq a (assoc (match-string 1 f) org-table-column-names))
7907      (setq f (replace-match (concat "$" (cdr a)) t t f)))
7908    ;; Parameters and constants
7909    (setq start 0)
7910    (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
7911      (setq start (1+ start))
7912      (if (setq a (save-match-data
7913		    (org-table-get-constant (match-string 1 f))))
7914	  (setq f (replace-match (concat "(" a ")") t t f))))
7915    (if org-table-formula-debug
7916	(put-text-property 0 (length f) :orig-formula f1 f))
7917    f))
7918
7919(defun org-table-get-constant (const)
7920  "Find the value for a parameter or constant in a formula.
7921Parameters get priority."
7922  (or (cdr (assoc const org-table-local-parameters))
7923      (cdr (assoc const org-table-formula-constants))
7924      (and (fboundp 'constants-get) (constants-get const))
7925      "#UNDEFINED_NAME"))
7926
7927(defvar org-edit-formulas-map (make-sparse-keymap))
7928(define-key org-edit-formulas-map "\C-c\C-c"      'org-finish-edit-formulas)
7929(define-key org-edit-formulas-map "\C-c\C-q"      'org-abort-edit-formulas)
7930(define-key org-edit-formulas-map "\C-c?"         'org-show-reference)
7931(define-key org-edit-formulas-map [(shift up)]    'org-table-edit-line-up)
7932(define-key org-edit-formulas-map [(shift down)]  'org-table-edit-line-down)
7933(define-key org-edit-formulas-map [(shift left)] 'org-table-edit-backward-field)
7934(define-key org-edit-formulas-map [(shift right)] 'org-table-edit-next-field)
7935(define-key org-edit-formulas-map [(meta up)]     'org-table-edit-scroll-down)
7936(define-key org-edit-formulas-map [(meta down)]   'org-table-edit-scroll)
7937(define-key org-edit-formulas-map [(meta tab)]    'lisp-complete-symbol)
7938(define-key org-edit-formulas-map "\M-\C-i"       'lisp-complete-symbol)
7939(define-key org-edit-formulas-map [(tab)]         'org-edit-formula-lisp-indent)
7940(define-key org-edit-formulas-map "\C-i"          'org-edit-formula-lisp-indent)
7941
7942(defvar org-pos)
7943
7944(defun org-table-edit-formulas ()
7945  "Edit the formulas of the current table in a separate buffer."
7946  (interactive)
7947  (unless (org-at-table-p) (error "Not at a table"))
7948  (org-table-get-specials)
7949  (let ((eql (org-table-get-stored-formulas))
7950	(pos (move-marker (make-marker) (point)))
7951	(wc (current-window-configuration))
7952	entry s)
7953    (switch-to-buffer-other-window "*Edit Formulas*")
7954    (erase-buffer)
7955    ;; Keep global-font-lock-mode from turning on font-lock-mode
7956    (let ((font-lock-global-modes '(not fundamental-mode)))
7957      (fundamental-mode))
7958    (org-set-local 'font-lock-global-modes (list 'not major-mode))
7959    (org-set-local 'org-pos pos)
7960    (org-set-local 'org-window-configuration wc)
7961    (use-local-map org-edit-formulas-map)
7962    (org-add-hook 'post-command-hook 'org-table-edit-formulas-post-command t t)
7963    (setq s "# `C-c C-c' to finish, `C-u C-c C-c' to also apply, `C-c C-q' to abort.
7964# `TAB' to pretty-print Lisp expressions, `M-TAB' to complete List symbols
7965# `M-up/down' to scroll table, `S-up/down' to change line for column formulas\n\n")
7966
7967    (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7968    (insert s)
7969    (while (setq entry (pop eql))
7970      (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
7971		      (car entry) " = " (cdr entry) "\n"))
7972      (remove-text-properties 0 (length s) '(face nil) s)
7973      (insert s))
7974    (goto-char (point-min))
7975    (message "Edit formulas and finish with `C-c C-c'.")))
7976
7977(defun org-table-edit-formulas-post-command ()
7978  (when (not (memq this-command '(lisp-complete-symbol)))
7979    (let ((win (selected-window)))
7980      (save-excursion
7981	(condition-case nil
7982	    (org-show-reference)
7983	  (error nil))
7984	(select-window win)))))
7985
7986(defun org-finish-edit-formulas (&optional arg)
7987  "Parse the buffer for formula definitions and install them.
7988With prefix ARG, apply the new formulas to the table."
7989  (interactive "P")
7990  (org-table-remove-rectangle-highlight)
7991  (let ((pos org-pos) eql var form)
7992    (setq org-pos nil)
7993    (goto-char (point-min))
7994    (while (re-search-forward
7995	    "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
7996	    nil t)
7997      (setq var (if (match-end 2) (match-string 2) (match-string 1))
7998	    form (match-string 3))
7999      (setq form (org-trim form))
8000      (while (string-match "[ \t]*\n[ \t]*" form)
8001	(setq form (replace-match " " t t form)))
8002      (push (cons var form) eql))
8003    (set-window-configuration org-window-configuration)
8004    (select-window (get-buffer-window (marker-buffer pos)))
8005    (goto-char pos)
8006    (unless (org-at-table-p)
8007      (error "Lost table position - cannot install formulae"))
8008    (org-table-store-formulas eql)
8009    (move-marker pos nil)
8010    (kill-buffer "*Edit Formulas*")
8011    (if arg
8012	(org-table-recalculate 'all)
8013      (message "New formulas installed - press C-u C-c C-c to apply."))))
8014
8015(defun org-abort-edit-formulas ()
8016  "Abort editing formulas, without installing the changes."
8017  (interactive)
8018  (org-table-remove-rectangle-highlight)
8019  (let ((pos org-pos))
8020    (set-window-configuration org-window-configuration)
8021    (select-window (get-buffer-window (marker-buffer pos)))
8022    (goto-char pos)
8023    (move-marker pos nil)
8024    (message "Formula editing aborted without installing changes")))
8025
8026(defun org-edit-formula-lisp-indent ()
8027  "Pretty-print and re-indent Lisp expressions in the Formula Editor."
8028  (interactive)
8029  (let ((pos (point)) beg end ind)
8030    (beginning-of-line 1)
8031    (cond
8032     ((looking-at "[ \t]")
8033      (goto-char pos)
8034      (call-interactively 'lisp-indent-line))
8035     ((looking-at "[$@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
8036     ((not (fboundp 'pp-buffer))
8037      (error "Cannot pretty-print.  Command `pp-buffer' is not available."))
8038     ((looking-at "[$@0-9a-zA-Z]+ *= *'(")
8039      (goto-char (- (match-end 0) 2))
8040      (setq beg (point))
8041      (setq ind (make-string (current-column) ?\ ))
8042      (condition-case nil (forward-sexp 1)
8043	(error
8044	 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
8045      (setq end (point))
8046      (save-restriction
8047	(narrow-to-region beg end)
8048	(if (eq last-command this-command)
8049	    (progn
8050	      (goto-char (point-min))
8051	      (setq this-command nil)
8052	      (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
8053		(replace-match " ")))
8054	  (pp-buffer)
8055	  (untabify (point-min) (point-max))
8056	  (goto-char (1+ (point-min)))
8057	  (while (re-search-forward "^." nil t)
8058	    (beginning-of-line 1)
8059	    (insert ind))
8060	  (goto-char (point-max))
8061	  (backward-delete-char 1)))
8062      (goto-char beg))
8063     (t nil))))
8064
8065(defvar org-show-positions nil)
8066
8067(defun org-show-reference (&optional local)
8068  "Show the location/value of the $ expression at point."
8069  (interactive)
8070  (org-table-remove-rectangle-highlight)
8071  (catch 'exit
8072    (let ((pos (if local (point) org-pos))
8073          (face2 'highlight)
8074          (org-inhibit-highlight-removal t)
8075	  (win (selected-window))
8076	  (org-show-positions nil)
8077	  var name e what match dest)
8078      (if local (org-table-get-specials))
8079      (setq what (cond
8080		  ((org-at-regexp-p org-table-range-regexp2) 'range)
8081		  ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
8082		  ((org-at-regexp-p "\\$[0-9]+") 'column)
8083		  ((not local) nil)
8084		  (t (error "No reference at point")))
8085	    match (and what (match-string 0)))
8086      (when (and  match (not (equal (match-beginning 0) (point-at-bol))))
8087	(org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
8088					 'secondary-selection))
8089      (org-add-hook 'before-change-functions
8090		    'org-table-remove-rectangle-highlight)
8091      (if (eq what 'name) (setq var (substring match 1)))
8092      (when (eq what 'range)
8093	(or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
8094	(setq match (org-table-formula-substitute-names match)))
8095      (unless local
8096	(save-excursion
8097	  (beginning-of-line 1)
8098	  (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\)=")
8099	    (setq dest (match-string 1))
8100	    (org-table-add-rectangle-overlay
8101	     (match-beginning 1) (match-end 1) face2))))
8102      (if (and (markerp pos) (marker-buffer pos))
8103	  (if (get-buffer-window (marker-buffer pos))
8104	      (select-window (get-buffer-window (marker-buffer pos)))
8105	    (switch-to-buffer-other-window (get-buffer-window
8106					    (marker-buffer pos)))))
8107      (goto-char pos)
8108      (org-table-force-dataline)
8109      (when dest
8110	(setq name (substring dest 1))
8111	(cond
8112	 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
8113	  (setq e (assoc name org-table-named-field-locations))
8114	  (goto-line (nth 1 e))
8115	  (org-table-goto-column (nth 2 e)))
8116	 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
8117	  (let ((l (string-to-number (match-string 1 dest)))
8118		(c (string-to-number (match-string 2 dest))))
8119	    (goto-line (aref org-table-dlines l))
8120	    (org-table-goto-column c)))
8121	 (t (org-table-goto-column (string-to-number name))))
8122	(move-marker pos (point))
8123	(org-table-highlight-rectangle nil nil face2))
8124      (cond
8125       ((equal dest match))
8126       ((not match))
8127       ((eq what 'range)
8128	(condition-case nil
8129	    (save-excursion
8130	      (org-table-get-range match nil nil 'highlight))
8131	  (error nil)))
8132       ((setq e (assoc var org-table-named-field-locations))
8133	(goto-line (nth 1 e))
8134	(org-table-goto-column (nth 2 e))
8135	(org-table-highlight-rectangle (point) (point))
8136	(message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
8137       ((setq e (assoc var org-table-column-names))
8138	(org-table-goto-column (string-to-number (cdr e)))
8139	(org-table-highlight-rectangle (point) (point))
8140	(goto-char (org-table-begin))
8141	(if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
8142			       (org-table-end) t)
8143	    (progn
8144	      (goto-char (match-beginning 1))
8145	      (org-table-highlight-rectangle)
8146	      (message "Named column (column %s)" (cdr e)))
8147	  (error "Column name not found")))
8148       ((eq what 'column)
8149	;; column number
8150	(org-table-goto-column (string-to-number (substring match 1)))
8151	(org-table-highlight-rectangle (point) (point))
8152	(message "Column %s" (substring match 1)))
8153       ((setq e (assoc var org-table-local-parameters))
8154	(goto-char (org-table-begin))
8155	(if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
8156	    (progn
8157	      (goto-char (match-beginning 1))
8158	      (org-table-highlight-rectangle)
8159	      (message "Local parameter."))
8160	  (error "Parameter not found")))
8161       (t
8162	(cond
8163	 ((not var) (error "No reference at point"))
8164	 ((setq e (assoc var org-table-formula-constants))
8165	  (message "Constant: $%s=%s in `org-table-formula-constants'."
8166		   var (cdr e)))
8167	 ((setq e (and (fboundp 'constants-get) (constants-get var)))
8168	  (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
8169	 (t (error "Undefined name $%s" var)))))
8170      (goto-char pos)
8171      (when org-show-positions
8172	(push pos org-show-positions)
8173	(let ((min (apply 'min org-show-positions))
8174	      (max (apply 'max org-show-positions)))
8175	  (when (or (not (pos-visible-in-window-p min))
8176		    (not (pos-visible-in-window-p max)))
8177	    (goto-char min)
8178	    (set-window-start (selected-window) (point-at-bol))
8179	    (goto-char pos))))
8180      (select-window win))))
8181
8182(defun org-table-force-dataline ()
8183  "Make sure the cursor is in a dataline in a table."
8184  (unless (save-excursion
8185	    (beginning-of-line 1)
8186	    (looking-at org-table-dataline-regexp))
8187    (let* ((re org-table-dataline-regexp)
8188	   (p1 (save-excursion (re-search-forward re nil 'move)))
8189	   (p2 (save-excursion (re-search-backward re nil 'move))))
8190      (cond ((and p1 p2)
8191	     (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
8192			    p1 p2)))
8193	    ((or p1 p2) (goto-char (or p1 p2)))
8194	    (t (error "No table dataline around here"))))))
8195
8196(defun org-table-edit-line-up ()
8197  "Move cursor one line up in the window showing the table."
8198  (interactive)
8199  (org-table-edit-move 'previous-line))
8200
8201(defun org-table-edit-line-down ()
8202  "Move cursor one line down in the window showing the table."
8203  (interactive)
8204 (org-table-edit-move 'next-line))
8205
8206(defun org-table-edit-backward-field ()
8207  "Move cursor one field backward in the window showing the table."
8208  (interactive)
8209  (org-table-edit-move 'org-table-previous-field))
8210
8211(defun org-table-edit-next-field ()
8212  "Move cursor one field forward in the window showing the table."
8213  (interactive)
8214  (org-table-edit-move 'org-table-next-field))
8215
8216(defun org-table-edit-move (command)
8217  "Move the cursor in the window shoinw the table.
8218Use COMMAND to do the motion, repeat if necessary to end up in a data line."
8219  (let ((org-table-allow-automatic-line-recalculation nil)
8220	(pos org-pos) (win (selected-window)) p)
8221    (select-window (get-buffer-window (marker-buffer org-pos)))
8222    (setq p (point))
8223    (call-interactively command)
8224    (while (and (org-at-table-p)
8225		(org-at-table-hline-p))
8226      (call-interactively command))
8227    (or (org-at-table-p) (goto-char p))
8228    (move-marker pos (point))
8229    (select-window win)))
8230
8231(defun org-table-edit-scroll (N)
8232  (interactive "p")
8233  (let ((other-window-scroll-buffer (marker-buffer org-pos)))
8234    (scroll-other-window N)))
8235
8236(defun org-table-edit-scroll-down (N)
8237  (interactive "p")
8238  (org-table-edit-scroll (- N)))
8239
8240(defvar org-table-rectangle-overlays nil)
8241
8242(defun org-table-add-rectangle-overlay (beg end &optional face)
8243  "Add a new overlay."
8244  (let ((ov (org-make-overlay beg end)))
8245    (org-overlay-put ov 'face (or face 'secondary-selection))
8246    (push ov org-table-rectangle-overlays)))
8247
8248(defun org-table-highlight-rectangle (&optional beg end face)
8249  "Highlight rectangular region in a table."
8250  (setq beg (or beg (point)) end (or end (point)))
8251  (let ((b (min beg end))
8252	(e (max beg end))
8253	l1 c1 l2 c2 tmp)
8254    (and (boundp 'org-show-positions)
8255	 (setq org-show-positions (cons b (cons e org-show-positions))))
8256    (goto-char (min beg end))
8257    (setq l1 (org-current-line)
8258	  c1 (org-table-current-column))
8259    (goto-char (max beg end))
8260    (setq l2 (org-current-line)
8261	  c2 (org-table-current-column))
8262    (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
8263    (goto-line l1)
8264    (beginning-of-line 1)
8265    (loop for line from l1 to l2 do
8266	  (when (looking-at org-table-dataline-regexp)
8267	    (org-table-goto-column c1)
8268	    (skip-chars-backward "^|\n") (setq beg (point))
8269	    (org-table-goto-column c2)
8270	    (skip-chars-forward "^|\n")  (setq end (point))
8271	    (org-table-add-rectangle-overlay beg end face))
8272	  (beginning-of-line 2))
8273    (goto-char b))
8274  (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
8275
8276(defun org-table-remove-rectangle-highlight (&rest ignore)
8277  "Remove the rectangle overlays."
8278  (unless org-inhibit-highlight-removal
8279    (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
8280    (mapc 'org-delete-overlay org-table-rectangle-overlays)
8281    (setq org-table-rectangle-overlays nil)))
8282
8283(defvar org-table-coordinate-overlays nil
8284  "Collects the cooordinate grid overlays, so that they can be removed.")
8285(make-variable-buffer-local 'org-table-coordinate-overlays)
8286
8287(defun org-table-overlay-coordinates ()
8288  "Add overlays to the table at point, to show row/column coordinates."
8289  (interactive)
8290  (mapc 'org-delete-overlay org-table-coordinate-overlays)
8291  (setq org-table-coordinate-overlays nil)
8292  (save-excursion
8293    (let ((id 0) (ih 0) hline eol str ic ov beg)
8294      (goto-char (org-table-begin))
8295      (while (org-at-table-p)
8296	(setq eol (point-at-eol))
8297	(setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
8298	(push ov org-table-coordinate-overlays)
8299	(setq hline (looking-at org-table-hline-regexp))
8300	(setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
8301		    (format "%4d" (setq id (1+ id)))))
8302	(org-overlay-before-string ov str 'org-formula 'evaporate)
8303	(when hline
8304	  (setq ic 0)
8305	  (while (re-search-forward "[+|]-+" eol t)
8306	    (setq beg (1+ (match-beginning 0))
8307		  str (concat "$" (int-to-string (setq ic (1+ ic)))))
8308	    (setq ov (org-make-overlay beg (+ beg (length str))))
8309	    (push ov org-table-coordinate-overlays)
8310	    (org-overlay-display ov str 'org-formula 'evaporate)))
8311	(beginning-of-line 2)))))
8312
8313(defun org-table-toggle-coordinate-overlays ()
8314  "Toggle the display of Row/Column numbers in tables."
8315  (interactive)
8316  (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
8317  (message "Row/Column number display turned %s"
8318	   (if org-table-overlay-coordinates "on" "off"))
8319  (if (and (org-at-table-p) org-table-overlay-coordinates)
8320      (org-table-align))
8321  (unless org-table-overlay-coordinates
8322    (mapc 'org-delete-overlay org-table-coordinate-overlays)
8323    (setq org-table-coordinate-overlays nil)))
8324
8325(defun org-table-toggle-formula-debugger ()
8326  "Toggle the formula debugger in tables."
8327  (interactive)
8328  (setq org-table-formula-debug (not org-table-formula-debug))
8329  (message "Formula debugging has been turned %s"
8330	   (if org-table-formula-debug "on" "off")))
8331
8332;;; The orgtbl minor mode
8333
8334;; Define a minor mode which can be used in other modes in order to
8335;; integrate the org-mode table editor.
8336
8337;; This is really a hack, because the org-mode table editor uses several
8338;; keys which normally belong to the major mode, for example the TAB and
8339;; RET keys.  Here is how it works: The minor mode defines all the keys
8340;; necessary to operate the table editor, but wraps the commands into a
8341;; function which tests if the cursor is currently inside a table.  If that
8342;; is the case, the table editor command is executed.  However, when any of
8343;; those keys is used outside a table, the function uses `key-binding' to
8344;; look up if the key has an associated command in another currently active
8345;; keymap (minor modes, major mode, global), and executes that command.
8346;; There might be problems if any of the keys used by the table editor is
8347;; otherwise used as a prefix key.
8348
8349;; Another challenge is that the key binding for TAB can be tab or \C-i,
8350;; likewise the binding for RET can be return or \C-m.  Orgtbl-mode
8351;; addresses this by checking explicitly for both bindings.
8352
8353;; The optimized version (see variable `orgtbl-optimized') takes over
8354;; all keys which are bound to `self-insert-command' in the *global map*.
8355;; Some modes bind other commands to simple characters, for example
8356;; AUCTeX binds the double quote to `Tex-insert-quote'.  With orgtbl-mode
8357;; active, this binding is ignored inside tables and replaced with a
8358;; modified self-insert.
8359
8360(defvar orgtbl-mode nil
8361  "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
8362table editor in arbitrary modes.")
8363(make-variable-buffer-local 'orgtbl-mode)
8364
8365(defvar orgtbl-mode-map (make-keymap)
8366  "Keymap for `orgtbl-mode'.")
8367
8368;;;###autoload
8369(defun turn-on-orgtbl ()
8370  "Unconditionally turn on `orgtbl-mode'."
8371  (orgtbl-mode 1))
8372
8373(defvar org-old-auto-fill-inhibit-regexp nil
8374  "Local variable used by `orgtbl-mode'")
8375
8376(defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
8377  "Matches a line belonging to an orgtbl.")
8378
8379(defconst orgtbl-extra-font-lock-keywords
8380  (list (list (concat "^" orgtbl-line-start-regexp ".*")
8381	      0 (quote 'org-table) 'prepend))
8382  "Extra font-lock-keywords to be added when orgtbl-mode is active.")
8383
8384;;;###autoload
8385(defun orgtbl-mode (&optional arg)
8386  "The `org-mode' table editor as a minor mode for use in other modes."
8387  (interactive)
8388  (if (org-mode-p)
8389      ;; Exit without error, in case some hook functions calls this
8390      ;; by accident in org-mode.
8391      (message "Orgtbl-mode is not useful in org-mode, command ignored")
8392    (setq orgtbl-mode
8393	  (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
8394    (if orgtbl-mode
8395	(progn
8396	  (and (orgtbl-setup) (defun orgtbl-setup () nil))
8397	  ;; Make sure we are first in minor-mode-map-alist
8398	  (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
8399	    (and c (setq minor-mode-map-alist
8400			 (cons c (delq c minor-mode-map-alist)))))
8401	  (org-set-local (quote org-table-may-need-update) t)
8402	  (org-add-hook 'before-change-functions 'org-before-change-function
8403			nil 'local)
8404	  (org-set-local 'org-old-auto-fill-inhibit-regexp
8405			 auto-fill-inhibit-regexp)
8406	  (org-set-local 'auto-fill-inhibit-regexp
8407			 (if auto-fill-inhibit-regexp
8408			     (concat orgtbl-line-start-regexp "\\|"
8409				     auto-fill-inhibit-regexp)
8410			   orgtbl-line-start-regexp))
8411	  (org-add-to-invisibility-spec '(org-cwidth))
8412	  (when (fboundp 'font-lock-add-keywords)
8413	    (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
8414	    (org-restart-font-lock))
8415	  (easy-menu-add orgtbl-mode-menu)
8416	  (run-hooks 'orgtbl-mode-hook))
8417      (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
8418      (org-cleanup-narrow-column-properties)
8419      (org-remove-from-invisibility-spec '(org-cwidth))
8420      (remove-hook 'before-change-functions 'org-before-change-function t)
8421      (when (fboundp 'font-lock-remove-keywords)
8422	(font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
8423	(org-restart-font-lock))
8424      (easy-menu-remove orgtbl-mode-menu)
8425      (force-mode-line-update 'all))))
8426
8427(defun org-cleanup-narrow-column-properties ()
8428  "Remove all properties related to narrow-column invisibility."
8429  (let ((s 1))
8430    (while (setq s (text-property-any s (point-max)
8431				      'display org-narrow-column-arrow))
8432      (remove-text-properties s (1+ s) '(display t)))
8433    (setq s 1)
8434    (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
8435      (remove-text-properties s (1+ s) '(org-cwidth t)))
8436    (setq s 1)
8437    (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
8438      (remove-text-properties s (1+ s) '(invisible t)))))
8439
8440;; Install it as a minor mode.
8441(put 'orgtbl-mode :included t)
8442(put 'orgtbl-mode :menu-tag "Org Table Mode")
8443(add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
8444
8445(defun orgtbl-make-binding (fun n &rest keys)
8446  "Create a function for binding in the table minor mode.
8447FUN is the command to call inside a table.  N is used to create a unique
8448command name.  KEYS are keys that should be checked in for a command
8449to execute outside of tables."
8450  (eval
8451   (list 'defun
8452	 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
8453	 '(arg)
8454	 (concat "In tables, run `" (symbol-name fun) "'.\n"
8455		 "Outside of tables, run the binding of `"
8456		 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8457		 "'.")
8458	 '(interactive "p")
8459	 (list 'if
8460	       '(org-at-table-p)
8461	       (list 'call-interactively (list 'quote fun))
8462	       (list 'let '(orgtbl-mode)
8463		     (list 'call-interactively
8464			   (append '(or)
8465				   (mapcar (lambda (k)
8466					     (list 'key-binding k))
8467					   keys)
8468				   '('orgtbl-error))))))))
8469
8470(defun orgtbl-error ()
8471  "Error when there is no default binding for a table key."
8472  (interactive)
8473  (error "This key is has no function outside tables"))
8474
8475(defun orgtbl-setup ()
8476  "Setup orgtbl keymaps."
8477  (let ((nfunc 0)
8478	(bindings
8479	 (list
8480	  '([(meta shift left)]  org-table-delete-column)
8481	  '([(meta left)]        org-table-move-column-left)
8482	  '([(meta right)]       org-table-move-column-right)
8483	  '([(meta shift right)] org-table-insert-column)
8484	  '([(meta shift up)]    org-table-kill-row)
8485	  '([(meta shift down)]  org-table-insert-row)
8486	  '([(meta up)]          org-table-move-row-up)
8487	  '([(meta down)]        org-table-move-row-down)
8488	  '("\C-c\C-w"           org-table-cut-region)
8489	  '("\C-c\M-w"           org-table-copy-region)
8490	  '("\C-c\C-y"           org-table-paste-rectangle)
8491	  '("\C-c-"              org-table-insert-hline)
8492	  '("\C-c}"              org-table-toggle-coordinate-overlays)
8493	  '("\C-c{"              org-table-toggle-formula-debugger)
8494	  '("\C-m"               org-table-next-row)
8495	  (list (org-key 'S-return) 'org-table-copy-down)
8496	  '("\C-c\C-q"           org-table-wrap-region)
8497	  '("\C-c?"              org-table-field-info)
8498	  '("\C-c "              org-table-blank-field)
8499	  '("\C-c+"              org-table-sum)
8500	  '("\C-c="              org-table-eval-formula)
8501	  '("\C-c'"              org-table-edit-formulas)
8502	  '("\C-c`"              org-table-edit-field)
8503	  '("\C-c*"              org-table-recalculate)
8504	  '("\C-c|"              org-table-create-or-convert-from-region)
8505	  '("\C-c^"              org-table-sort-lines)
8506	  '([(control ?#)]       org-table-rotate-recalc-marks)))
8507	elt key fun cmd)
8508    (while (setq elt (pop bindings))
8509      (setq nfunc (1+ nfunc))
8510      (setq key (car elt)
8511	    fun (nth 1 elt)
8512	    cmd (orgtbl-make-binding fun nfunc key))
8513      (define-key orgtbl-mode-map key cmd))
8514
8515    ;; Special treatment needed for TAB and RET
8516    (define-key orgtbl-mode-map [(return)]
8517      (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
8518    (define-key orgtbl-mode-map "\C-m"
8519      (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
8520
8521    (define-key orgtbl-mode-map [(tab)]
8522      (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
8523    (define-key orgtbl-mode-map "\C-i"
8524      (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
8525
8526    (define-key orgtbl-mode-map [(shift tab)]
8527      (orgtbl-make-binding 'org-table-previous-field 104
8528			   [(shift tab)] [(tab)] "\C-i"))
8529
8530    (define-key orgtbl-mode-map "\M-\C-m"
8531      (orgtbl-make-binding 'org-table-wrap-region 105
8532			   "\M-\C-m" [(meta return)]))
8533    (define-key orgtbl-mode-map [(meta return)]
8534      (orgtbl-make-binding 'org-table-wrap-region 106
8535			   [(meta return)] "\M-\C-m"))
8536
8537    (define-key orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
8538    (when orgtbl-optimized
8539      ;; If the user wants maximum table support, we need to hijack
8540      ;; some standard editing functions
8541      (org-remap orgtbl-mode-map
8542		 'self-insert-command 'orgtbl-self-insert-command
8543		 'delete-char 'org-delete-char
8544		 'delete-backward-char 'org-delete-backward-char)
8545      (define-key orgtbl-mode-map "|" 'org-force-self-insert))
8546    (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
8547      '("OrgTbl"
8548	["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
8549	["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
8550	["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
8551	["Next Row" org-return :active (org-at-table-p) :keys "RET"]
8552	"--"
8553	["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
8554	["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
8555	["Copy Field from Above"
8556	 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
8557	"--"
8558	("Column"
8559	 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
8560	 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
8561	 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
8562	 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
8563	("Row"
8564	 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
8565	 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
8566	 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
8567	 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
8568	 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
8569	 "--"
8570	 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
8571	("Rectangle"
8572	 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
8573	 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
8574	 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
8575	 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
8576	"--"
8577	("Radio tables"
8578	 ["Insert table template" orgtbl-insert-radio-table
8579	  (assq major-mode orgtbl-radio-table-templates)]
8580	 ["Comment/uncomment table" orgtbl-toggle-comment t])
8581	"--"
8582	["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
8583	["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
8584	["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
8585	["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
8586	["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
8587	["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
8588	["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
8589	["Sum Column/Rectangle" org-table-sum
8590	 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
8591	["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
8592	["Debug Formulas"
8593	 org-table-toggle-formula-debugger :active (org-at-table-p)
8594	 :keys "C-c {"
8595	 :style toggle :selected org-table-formula-debug]
8596	["Show Col/Row Numbers"
8597	 org-table-toggle-coordinate-overlays :active (org-at-table-p)
8598	 :keys "C-c }"
8599	 :style toggle :selected org-table-overlay-coordinates]
8600	))
8601    t))
8602
8603(defun orgtbl-ctrl-c-ctrl-c (arg)
8604  "If the cursor is inside a table, realign the table.
8605It it is a table to be sent away to a receiver, do it.
8606With prefix arg, also recompute table."
8607  (interactive "P")
8608  (let ((pos (point)) action)
8609    (save-excursion
8610      (beginning-of-line 1)
8611      (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
8612			 ((looking-at "[ \t]*|") pos)
8613			 ((looking-at "#\\+TBLFM:") 'recalc))))
8614    (cond
8615     ((integerp action)
8616      (goto-char action)
8617      (org-table-maybe-eval-formula)
8618      (if arg
8619	  (call-interactively 'org-table-recalculate)
8620	(org-table-maybe-recalculate-line))
8621      (call-interactively 'org-table-align)
8622      (orgtbl-send-table 'maybe))
8623     ((eq action 'recalc)
8624      (save-excursion
8625	(beginning-of-line 1)
8626	(skip-chars-backward " \r\n\t")
8627	(if (org-at-table-p)
8628	    (org-call-with-arg 'org-table-recalculate t))))
8629     (t (let (orgtbl-mode)
8630	  (call-interactively (key-binding "\C-c\C-c")))))))
8631
8632(defun orgtbl-tab (arg)
8633  "Justification and field motion for `orgtbl-mode'."
8634  (interactive "P")
8635  (if arg (org-table-edit-field t)
8636    (org-table-justify-field-maybe)
8637    (org-table-next-field)))
8638
8639(defun orgtbl-ret ()
8640  "Justification and field motion for `orgtbl-mode'."
8641  (interactive)
8642  (org-table-justify-field-maybe)
8643  (org-table-next-row))
8644
8645(defun orgtbl-self-insert-command (N)
8646  "Like `self-insert-command', use overwrite-mode for whitespace in tables.
8647If the cursor is in a table looking at whitespace, the whitespace is
8648overwritten, and the table is not marked as requiring realignment."
8649  (interactive "p")
8650  (if (and (org-at-table-p)
8651	   (or
8652	    (and org-table-auto-blank-field
8653		 (member last-command
8654			 '(orgtbl-hijacker-command-100
8655			   orgtbl-hijacker-command-101
8656			   orgtbl-hijacker-command-102
8657			   orgtbl-hijacker-command-103
8658			   orgtbl-hijacker-command-104
8659			   orgtbl-hijacker-command-105))
8660		 (org-table-blank-field))
8661	    t)
8662	   (eq N 1)
8663	   (looking-at "[^|\n]*  +|"))
8664      (let (org-table-may-need-update)
8665	(goto-char (1- (match-end 0)))
8666	(delete-backward-char 1)
8667	(goto-char (match-beginning 0))
8668	(self-insert-command N))
8669    (setq org-table-may-need-update t)
8670    (let (orgtbl-mode)
8671      (call-interactively (key-binding (vector last-input-event))))))
8672
8673(defun org-force-self-insert (N)
8674  "Needed to enforce self-insert under remapping."
8675  (interactive "p")
8676  (self-insert-command N))
8677
8678(defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
8679  "Regula expression matching exponentials as produced by calc.")
8680
8681(defvar org-table-clean-did-remove-column-1 nil)
8682
8683(defun orgtbl-send-table (&optional maybe)
8684  "Send a tranformed version of this table to the receiver position.
8685With argument MAYBE, fail quietly if no transformation is defined for
8686this table."
8687  (interactive)
8688  (catch 'exit
8689    (unless (org-at-table-p) (error "Not at a table"))
8690    ;; when non-interactive, we assume align has just happened.
8691    (when (interactive-p) (org-table-align))
8692    (save-excursion
8693      (goto-char (org-table-begin))
8694      (beginning-of-line 0)
8695      (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
8696	(if maybe
8697	    (throw 'exit nil)
8698	  (error "Don't know how to transform this table."))))
8699    (let* ((name (match-string 1))
8700	   beg
8701	   (transform (intern (match-string 2)))
8702	   (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
8703	   (skip (plist-get params :skip))
8704	   (skipcols (plist-get params :skipcols))
8705	   (txt (buffer-substring-no-properties
8706		 (org-table-begin) (org-table-end)))
8707	   (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
8708	   (lines (org-table-clean-before-export lines))
8709	   (i0 (if org-table-clean-did-remove-column-1 2 1))
8710	   (table (mapcar
8711		   (lambda (x)
8712		     (if (string-match org-table-hline-regexp x)
8713			 'hline
8714		       (org-remove-by-index
8715			(org-split-string (org-trim x) "\\s-*|\\s-*")
8716			skipcols i0)))
8717		   lines))
8718	   (fun (if (= i0 2) 'cdr 'identity))
8719	   (org-table-last-alignment
8720	    (org-remove-by-index (funcall fun org-table-last-alignment)
8721				 skipcols i0))
8722	   (org-table-last-column-widths
8723	    (org-remove-by-index (funcall fun org-table-last-column-widths)
8724				 skipcols i0)))
8725
8726      (unless (fboundp transform)
8727	(error "No such transformation function %s" transform))
8728      (setq txt (funcall transform table params))
8729      ;; Find the insertion place
8730      (save-excursion
8731	(goto-char (point-min))
8732	(unless (re-search-forward
8733		 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
8734	  (error "Don't know where to insert translated table"))
8735	(goto-char (match-beginning 0))
8736	(beginning-of-line 2)
8737	(setq beg (point))
8738	(unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
8739	  (error "Cannot find end of insertion region"))
8740	(beginning-of-line 1)
8741	(delete-region beg (point))
8742	(goto-char beg)
8743	(insert txt "\n"))
8744      (message "Table converted and installed at receiver location"))))
8745
8746(defun org-remove-by-index (list indices &optional i0)
8747  "Remove the elements in LIST with indices in INDICES.
8748First element has index 0, or I0 if given."
8749  (if (not indices)
8750      list
8751    (if (integerp indices) (setq indices (list indices)))
8752    (setq i0 (1- (or i0 0)))
8753    (delq :rm (mapcar (lambda (x)
8754			(setq i0 (1+ i0))
8755			(if (memq i0 indices) :rm x))
8756		      list))))
8757
8758(defun orgtbl-toggle-comment ()
8759  "Comment or uncomment the orgtbl at point."
8760  (interactive)
8761  (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
8762	 (re2 (concat "^" orgtbl-line-start-regexp))
8763	 (commented (save-excursion (beginning-of-line 1)
8764			     (cond ((looking-at re1) t)
8765				   ((looking-at re2) nil)
8766				   (t (error "Not at an org table")))))
8767	 (re (if commented re1 re2))
8768	 beg end)
8769    (save-excursion
8770      (beginning-of-line 1)
8771      (while (looking-at re) (beginning-of-line 0))
8772      (beginning-of-line 2)
8773      (setq beg (point))
8774      (while (looking-at re) (beginning-of-line 2))
8775      (setq end (point)))
8776    (comment-region beg end (if commented '(4) nil))))
8777
8778(defun orgtbl-insert-radio-table ()
8779  "Insert a radio table template appropriate for this major mode."
8780  (interactive)
8781  (let* ((e (assq major-mode orgtbl-radio-table-templates))
8782	 (txt (nth 1 e))
8783	 name pos)
8784    (unless e (error "No radio table setup defined for %s" major-mode))
8785    (setq name (read-string "Table name: "))
8786    (while (string-match "%n" txt)
8787      (setq txt (replace-match name t t txt)))
8788    (or (bolp) (insert "\n"))
8789    (setq pos (point))
8790    (insert txt)
8791    (goto-char pos)))
8792
8793(defun org-get-param (params header i sym &optional hsym)
8794  "Get parameter value for symbol SYM.
8795If this is a header line, actually get the value for the symbol with an
8796additional \"h\" inserted after the colon.
8797If the value is a protperty list, get the element for the current column.
8798Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
8799  (let ((val (plist-get params sym)))
8800    (and hsym header (setq val (or (plist-get params hsym) val)))
8801    (if (consp val) (plist-get val i) val)))
8802
8803(defun orgtbl-to-generic (table params)
8804  "Convert the orgtbl-mode TABLE to some other format.
8805This generic routine can be used for many standard cases.
8806TABLE is a list, each entry either the symbol `hline' for a horizontal
8807separator line, or a list of fields for that line.
8808PARAMS is a property list of parameters that can influence the conversion.
8809For the generic converter, some parameters are obligatory:  You need to
8810specify either :lfmt, or all of (:lstart :lend :sep).  If you do not use
8811:splice, you must have :tstart and :tend.
8812
8813Valid parameters are
8814
8815:tstart     String to start the table.  Ignored when :splice is t.
8816:tend       String to end the table.  Ignored when :splice is t.
8817
8818:splice     When set to t, return only table body lines, don't wrap
8819            them into :tstart and :tend.  Default is nil.
8820
8821:hline      String to be inserted on horizontal separation lines.
8822            May be nil to ignore hlines.
8823
8824:lstart     String to start a new table line.
8825:lend       String to end a table line
8826:sep        Separator between two fields
8827:lfmt       Format for entire line, with enough %s to capture all fields.
8828            If this is present, :lstart, :lend, and :sep are ignored.
8829:fmt        A format to be used to wrap the field, should contain
8830            %s for the original field value.  For example, to wrap
8831            everything in dollars, you could use :fmt \"$%s$\".
8832            This may also be a property list with column numbers and
8833            formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
8834
8835:hlstart :hlend :hlsep :hlfmt :hfmt
8836            Same as above, specific for the header lines in the table.
8837            All lines before the first hline are treated as header.
8838            If any of these is not present, the data line value is used.
8839
8840:efmt       Use this format to print numbers with exponentials.
8841            The format should have %s twice for inserting mantissa
8842            and exponent, for example \"%s\\\\times10^{%s}\".  This
8843            may also be a property list with column numbers and
8844            formats.  :fmt will still be applied after :efmt.
8845
8846In addition to this, the parameters :skip and :skipcols are always handled
8847directly by `orgtbl-send-table'.  See manual."
8848  (interactive)
8849  (let* ((p params)
8850	 (splicep (plist-get p :splice))
8851	 (hline (plist-get p :hline))
8852	 rtn line i fm efm lfmt h)
8853
8854    ;; Do we have a header?
8855    (if (and (not splicep) (listp (car table)) (memq 'hline table))
8856	(setq h t))
8857
8858    ;; Put header
8859    (unless splicep
8860      (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
8861
8862    ;; Now loop over all lines
8863    (while (setq line (pop table))
8864      (if (eq line 'hline)
8865	  ;; A horizontal separator line
8866	  (progn (if hline (push hline rtn))
8867		 (setq h nil))               ; no longer in header
8868	;; A normal line.  Convert the fields, push line onto the result list
8869	(setq i 0)
8870	(setq line
8871	      (mapcar
8872	       (lambda (f)
8873		 (setq i (1+ i)
8874		       fm (org-get-param p h i :fmt :hfmt)
8875		       efm (org-get-param p h i :efmt))
8876		 (if (and efm (string-match orgtbl-exp-regexp f))
8877		     (setq f (format
8878			      efm (match-string 1 f) (match-string 2 f))))
8879		 (if fm (setq f (format fm f)))
8880		 f)
8881	       line))
8882	(if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
8883	    (push (apply 'format lfmt line) rtn)
8884	  (push (concat
8885		 (org-get-param p h i :lstart :hlstart)
8886		 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
8887		 (org-get-param p h i :lend :hlend))
8888		rtn))))
8889
8890    (unless splicep
8891      (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
8892
8893    (mapconcat 'identity (nreverse rtn) "\n")))
8894
8895(defun orgtbl-to-latex (table params)
8896  "Convert the orgtbl-mode TABLE to LaTeX.
8897TABLE is a list, each entry either the symbol `hline' for a horizontal
8898separator line, or a list of fields for that line.
8899PARAMS is a property list of parameters that can influence the conversion.
8900Supports all parameters from `orgtbl-to-generic'.  Most important for
8901LaTeX are:
8902
8903:splice    When set to t, return only table body lines, don't wrap
8904           them into a tabular environment.  Default is nil.
8905
8906:fmt       A format to be used to wrap the field, should contain %s for the
8907           original field value.  For example, to wrap everything in dollars,
8908           use :fmt \"$%s$\".  This may also be a property list with column
8909           numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
8910
8911:efmt      Format for transforming numbers with exponentials.  The format
8912           should have %s twice for inserting mantissa and exponent, for
8913           example \"%s\\\\times10^{%s}\".  LaTeX default is \"%s\\\\,(%s)\".
8914           This may also be a property list with column numbers and formats.
8915
8916The general parameters :skip and :skipcols have already been applied when
8917this function is called."
8918  (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
8919			       org-table-last-alignment ""))
8920	 (params2
8921	  (list
8922	   :tstart (concat "\\begin{tabular}{" alignment "}")
8923	   :tend "\\end{tabular}"
8924	   :lstart "" :lend " \\\\" :sep " & "
8925	   :efmt "%s\\,(%s)" :hline "\\hline")))
8926    (orgtbl-to-generic table (org-combine-plists params2 params))))
8927
8928(defun orgtbl-to-html (table params)
8929  "Convert the orgtbl-mode TABLE to LaTeX.
8930TABLE is a list, each entry either the symbol `hline' for a horizontal
8931separator line, or a list of fields for that line.
8932PARAMS is a property list of parameters that can influence the conversion.
8933Currently this function recognizes the following parameters:
8934
8935:splice    When set to t, return only table body lines, don't wrap
8936           them into a <table> environment.  Default is nil.
8937
8938The general parameters :skip and :skipcols have already been applied when
8939this function is called.  The function does *not* use `orgtbl-to-generic',
8940so you cannot specify parameters for it."
8941  (let* ((splicep (plist-get params :splice))
8942	 html)
8943    ;; Just call the formatter we already have
8944    ;; We need to make text lines for it, so put the fields back together.
8945    (setq html (org-format-org-table-html
8946		(mapcar
8947		 (lambda (x)
8948		   (if (eq x 'hline)
8949		       "|----+----|"
8950		     (concat "| " (mapconcat 'identity x " | ") " |")))
8951		 table)
8952		splicep))
8953    (if (string-match "\n+\\'" html)
8954	(setq html (replace-match "" t t html)))
8955    html))
8956
8957(defun orgtbl-to-texinfo (table params)
8958  "Convert the orgtbl-mode TABLE to TeXInfo.
8959TABLE is a list, each entry either the symbol `hline' for a horizontal
8960separator line, or a list of fields for that line.
8961PARAMS is a property list of parameters that can influence the conversion.
8962Supports all parameters from `orgtbl-to-generic'.  Most important for
8963TeXInfo are:
8964
8965:splice nil/t      When set to t, return only table body lines, don't wrap
8966                   them into a multitable environment.  Default is nil.
8967
8968:fmt fmt           A format to be used to wrap the field, should contain
8969                   %s for the original field value.  For example, to wrap
8970                   everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
8971                   This may also be a property list with column numbers and
8972                   formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
8973
8974:cf \"f1 f2..\"    The column fractions for the table.  Bye default these
8975                   are computed automatically from the width of the columns
8976                   under org-mode.
8977
8978The general parameters :skip and :skipcols have already been applied when
8979this function is called."
8980  (let* ((total (float (apply '+ org-table-last-column-widths)))
8981	 (colfrac (or (plist-get params :cf)
8982		      (mapconcat
8983		       (lambda (x) (format "%.3f" (/ (float x) total)))
8984		       org-table-last-column-widths " ")))
8985	 (params2
8986	  (list
8987	   :tstart (concat "@multitable @columnfractions " colfrac)
8988	   :tend "@end multitable"
8989	   :lstart "@item " :lend "" :sep " @tab "
8990	   :hlstart "@headitem ")))
8991    (orgtbl-to-generic table (org-combine-plists params2 params))))
8992
8993;;;; Link Stuff
8994
8995;;; Link abbreviations
8996
8997(defun org-link-expand-abbrev (link)
8998  "Apply replacements as defined in `org-link-abbrev-alist."
8999  (if (string-match "^\\([a-zA-Z]+\\)\\(::?\\(.*\\)\\)?$" link)
9000      (let* ((key (match-string 1 link))
9001	     (as (or (assoc key org-link-abbrev-alist-local)
9002		     (assoc key org-link-abbrev-alist)))
9003	     (tag (and (match-end 2) (match-string 3 link)))
9004	     rpl)
9005	(if (not as)
9006	    link
9007	  (setq rpl (cdr as))
9008	  (cond
9009	   ((symbolp rpl) (funcall rpl tag))
9010	   ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9011	   (t (concat rpl tag)))))
9012    link))
9013
9014;;; Storing and inserting links
9015
9016(defvar org-insert-link-history nil
9017  "Minibuffer history for links inserted with `org-insert-link'.")
9018
9019(defvar org-stored-links nil
9020  "Contains the links stored with `org-store-link'.")
9021
9022(defvar org-store-link-plist nil
9023  "Plist with info about the most recently link created with `org-store-link'.")
9024
9025;;;###autoload
9026(defun org-store-link (arg)
9027  "\\<org-mode-map>Store an org-link to the current location.
9028This link can later be inserted into an org-buffer with
9029\\[org-insert-link].
9030For some link types, a prefix arg is interpreted:
9031For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
9032For file links, arg negates `org-context-in-file-links'."
9033  (interactive "P")
9034  (setq org-store-link-plist nil)  ; reset
9035  (let (link cpltxt desc description search txt)
9036    (cond
9037
9038     ((eq major-mode 'bbdb-mode)
9039      (let ((name (bbdb-record-name (bbdb-current-record)))
9040	    (company (bbdb-record-company (bbdb-current-record))))
9041	(setq cpltxt (concat "bbdb:" (or name company))
9042	      link (org-make-link cpltxt))
9043	(org-store-link-props :type "bbdb" :name name :company company)))
9044
9045     ((eq major-mode 'Info-mode)
9046      (setq link (org-make-link "info:"
9047				(file-name-nondirectory Info-current-file)
9048				":" Info-current-node))
9049      (setq cpltxt (concat (file-name-nondirectory Info-current-file)
9050			   ":" Info-current-node))
9051      (org-store-link-props :type "info" :file Info-current-file
9052			    :node Info-current-node))
9053
9054     ((eq major-mode 'calendar-mode)
9055      (let ((cd (calendar-cursor-to-date)))
9056	(setq link
9057	      (format-time-string
9058	       (car org-time-stamp-formats)
9059	       (apply 'encode-time
9060		      (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9061			    nil nil nil))))
9062	(org-store-link-props :type "calendar" :date cd)))
9063
9064     ((or (eq major-mode 'vm-summary-mode)
9065	  (eq major-mode 'vm-presentation-mode))
9066      (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
9067      (vm-follow-summary-cursor)
9068      (save-excursion
9069       (vm-select-folder-buffer)
9070       (let* ((message (car vm-message-pointer))
9071	      (folder buffer-file-name)
9072	      (subject (vm-su-subject message))
9073	      (to (vm-get-header-contents message "To"))
9074	      (from (vm-get-header-contents message "From"))
9075	      (message-id (vm-su-message-id message)))
9076	 (org-store-link-props :type "vm" :from from :to to :subject subject
9077			       :message-id message-id)
9078	 (setq message-id (org-remove-angle-brackets message-id))
9079	 (setq folder (abbreviate-file-name folder))
9080	 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
9081			   folder)
9082	     (setq folder (replace-match "" t t folder)))
9083	 (setq cpltxt (org-email-link-description))
9084	 (setq link (org-make-link "vm:" folder "#" message-id)))))
9085
9086     ((eq major-mode 'wl-summary-mode)
9087      (let* ((msgnum (wl-summary-message-number))
9088	     (message-id (elmo-message-field wl-summary-buffer-elmo-folder
9089					     msgnum 'message-id))
9090	     (wl-message-entity
9091	      (if (fboundp 'elmo-message-entity)
9092		  (elmo-message-entity
9093		   wl-summary-buffer-elmo-folder msgnum)
9094		  (elmo-msgdb-overview-get-entity
9095		   msgnum (wl-summary-buffer-msgdb))))
9096	     (from (wl-summary-line-from))
9097	     (to (car (elmo-message-entity-field wl-message-entity 'to)))
9098	     (subject (let (wl-thr-indent-string wl-parent-message-entity)
9099			(wl-summary-line-subject))))
9100	(org-store-link-props :type "wl" :from from :to to
9101			      :subject subject :message-id message-id)
9102	(setq message-id (org-remove-angle-brackets message-id))
9103	(setq cpltxt (org-email-link-description))
9104	(setq link (org-make-link "wl:" wl-summary-buffer-folder-name
9105				  "#" message-id))))
9106
9107     ((or (equal major-mode 'mh-folder-mode)
9108	  (equal major-mode 'mh-show-mode))
9109      (let ((from (org-mhe-get-header "From:"))
9110	    (to (org-mhe-get-header "To:"))
9111	    (message-id (org-mhe-get-header "Message-Id:"))
9112	    (subject (org-mhe-get-header "Subject:")))
9113	(org-store-link-props :type "mh" :from from :to to
9114			      :subject subject :message-id message-id)
9115	(setq cpltxt (org-email-link-description))
9116	(setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
9117				  (org-remove-angle-brackets message-id)))))
9118
9119     ((eq major-mode 'rmail-mode)
9120      (save-excursion
9121	(save-restriction
9122	  (rmail-narrow-to-non-pruned-header)
9123	  (let ((folder buffer-file-name)
9124		(message-id (mail-fetch-field "message-id"))
9125		(from (mail-fetch-field "from"))
9126		(to (mail-fetch-field "to"))
9127		(subject (mail-fetch-field "subject")))
9128	    (org-store-link-props
9129	     :type "rmail" :from from :to to
9130	     :subject subject :message-id message-id)
9131	    (setq message-id (org-remove-angle-brackets message-id))
9132	    (setq cpltxt (org-email-link-description))
9133	    (setq link (org-make-link "rmail:" folder "#" message-id))))))
9134
9135     ((eq major-mode 'gnus-group-mode)
9136      (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
9137			  (gnus-group-group-name))         ; version
9138			 ((fboundp 'gnus-group-name)
9139			  (gnus-group-name))
9140			 (t "???"))))
9141	(unless group (error "Not on a group"))
9142	(org-store-link-props :type "gnus" :group group)
9143	(setq cpltxt (concat
9144		      (if (org-xor arg org-usenet-links-prefer-google)
9145			  "http://groups.google.com/groups?group="
9146			"gnus:")
9147		      group)
9148	      link (org-make-link cpltxt))))
9149
9150     ((memq major-mode '(gnus-summary-mode gnus-article-mode))
9151      (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
9152      (let* ((group gnus-newsgroup-name)
9153	     (article (gnus-summary-article-number))
9154	     (header (gnus-summary-article-header article))
9155	     (from (mail-header-from header))
9156	     (message-id (mail-header-id header))
9157	     (date (mail-header-date header))
9158	     (subject (gnus-summary-subject-string)))
9159	(org-store-link-props :type "gnus" :from from :subject subject
9160			      :message-id message-id :group group)
9161	(setq cpltxt (org-email-link-description))
9162	(if (org-xor arg org-usenet-links-prefer-google)
9163	    (setq link
9164		  (concat
9165		   cpltxt "\n  "
9166		   (format "http://groups.google.com/groups?as_umsgid=%s"
9167			   (org-fixup-message-id-for-http message-id))))
9168	  (setq link (org-make-link "gnus:" group
9169				    "#" (number-to-string article))))))
9170
9171     ((eq major-mode 'w3-mode)
9172      (setq cpltxt (url-view-url t)
9173	    link (org-make-link cpltxt))
9174      (org-store-link-props :type "w3" :url (url-view-url t)))
9175
9176     ((eq major-mode 'w3m-mode)
9177      (setq cpltxt (or w3m-current-title w3m-current-url)
9178	    link (org-make-link w3m-current-url))
9179      (org-store-link-props :type "w3m" :url (url-view-url t)))
9180
9181     ((setq search (run-hook-with-args-until-success
9182		    'org-create-file-search-functions))
9183      (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9184			 "::" search))
9185      (setq cpltxt (or description link)))
9186
9187     ((eq major-mode 'image-mode)
9188      (setq cpltxt (concat "file:"
9189			   (abbreviate-file-name buffer-file-name))
9190	    link (org-make-link cpltxt))
9191      (org-store-link-props :type "image" :file buffer-file-name))
9192
9193     ((eq major-mode 'dired-mode)
9194      ;; link to the file in the current line
9195      (setq cpltxt (concat "file:"
9196			   (abbreviate-file-name
9197			    (expand-file-name
9198			     (dired-get-filename nil t))))
9199	    link (org-make-link cpltxt)))
9200
9201     ((and buffer-file-name (org-mode-p))
9202      ;; Just link to current headline
9203      (setq cpltxt (concat "file:"
9204			   (abbreviate-file-name buffer-file-name)))
9205      ;; Add a context search string
9206      (when (org-xor org-context-in-file-links arg)
9207	;; Check if we are on a target
9208	(if (org-in-regexp "<<\\(.*?\\)>>")
9209	    (setq cpltxt (concat cpltxt "::" (match-string 1)))
9210	  (setq txt (cond
9211		     ((org-on-heading-p) nil)
9212		     ((org-region-active-p)
9213		      (buffer-substring (region-beginning) (region-end)))
9214		     (t (buffer-substring (point-at-bol) (point-at-eol)))))
9215	  (when (or (null txt) (string-match "\\S-" txt))
9216	    (setq cpltxt
9217		  (concat cpltxt "::" (org-make-org-heading-search-string txt))
9218		  desc "NONE"))))
9219      (if (string-match "::\\'" cpltxt)
9220	  (setq cpltxt (substring cpltxt 0 -2)))
9221      (setq link (org-make-link cpltxt)))
9222
9223     (buffer-file-name
9224      ;; Just link to this file here.
9225      (setq cpltxt (concat "file:"
9226			   (abbreviate-file-name buffer-file-name)))
9227      ;; Add a context string
9228      (when (org-xor org-context-in-file-links arg)
9229	(setq txt (if (org-region-active-p)
9230		      (buffer-substring (region-beginning) (region-end))
9231		    (buffer-substring (point-at-bol) (point-at-eol))))
9232	;; Only use search option if there is some text.
9233	(when (string-match "\\S-" txt)
9234	  (setq cpltxt
9235		(concat cpltxt "::" (org-make-org-heading-search-string txt))
9236		desc "NONE")))
9237      (setq link (org-make-link cpltxt)))
9238
9239     ((interactive-p)
9240      (error "Cannot link to a buffer which is not visiting a file"))
9241
9242     (t (setq link nil)))
9243
9244    (if (consp link) (setq cpltxt (car link) link (cdr link)))
9245    (setq link (or link cpltxt)
9246	  desc (or desc cpltxt))
9247    (if (equal desc "NONE") (setq desc nil))
9248
9249    (if (and (interactive-p) link)
9250	(progn
9251	  (setq org-stored-links
9252		(cons (list cpltxt link desc) org-stored-links))
9253	  (message "Stored: %s" (or cpltxt link)))
9254      (org-make-link-string link desc))))
9255
9256(defun org-store-link-props (&rest plist)
9257  "Store link properties, extract names and addresses."
9258  (let (x adr)
9259    (when (setq x (plist-get plist :from))
9260      (setq adr (mail-extract-address-components x))
9261      (plist-put plist :fromname (car adr))
9262      (plist-put plist :fromaddress (nth 1 adr)))
9263    (when (setq x (plist-get plist :to))
9264      (setq adr (mail-extract-address-components x))
9265      (plist-put plist :toname (car adr))
9266      (plist-put plist :toaddress (nth 1 adr))))
9267  (let ((from (plist-get plist :from))
9268	(to (plist-get plist :to)))
9269    (when (and from to org-from-is-user-regexp)
9270      (plist-put plist :fromto
9271		 (if (string-match org-from-is-user-regexp from)
9272		     (concat "to %t")
9273		   (concat "from %f")))))
9274  (setq org-store-link-plist plist))
9275
9276(defun org-email-link-description (&optional fmt)
9277  "Return the description part of an email link.
9278This takes information from `org-store-link-plist' and formats it
9279according to FMT (default from `org-email-link-description-format')."
9280  (setq fmt (or fmt org-email-link-description-format))
9281  (let* ((p org-store-link-plist)
9282	 (to (plist-get p :toaddress))
9283	 (from (plist-get p :fromaddress))
9284	 (table
9285	  (list
9286	   (cons "%c" (plist-get p :fromto))
9287	   (cons "%F" (plist-get p :from))
9288	   (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9289	   (cons "%T" (plist-get p :to))
9290	   (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9291	   (cons "%s" (plist-get p :subject))
9292	   (cons "%m" (plist-get p :message-id)))))
9293    (when (string-match "%c" fmt)
9294      ;; Check if the user wrote this message
9295      (if (and org-from-is-user-regexp from to
9296	       (save-match-data (string-match org-from-is-user-regexp from)))
9297	  (setq fmt (replace-match "to %t" t t fmt))
9298	(setq fmt (replace-match "from %f" t t fmt))))
9299    (org-replace-escapes fmt table)))
9300
9301(defun org-make-org-heading-search-string (&optional string heading)
9302  "Make search string for STRING or current headline."
9303  (interactive)
9304  (let ((s (or string (org-get-heading))))
9305    (unless (and string (not heading))
9306      ;; We are using a headline, clean up garbage in there.
9307      (if (string-match org-todo-regexp s)
9308	  (setq s (replace-match "" t t s)))
9309      (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
9310	  (setq s (replace-match "" t t s)))
9311      (setq s (org-trim s))
9312      (if (string-match (concat "^\\(" org-quote-string "\\|"
9313				org-comment-string "\\)") s)
9314	  (setq s (replace-match "" t t s)))
9315      (while (string-match org-ts-regexp s)
9316	(setq s (replace-match "" t t s))))
9317    (while (string-match "[^a-zA-Z_0-9 \t]+" s)
9318      (setq s (replace-match " " t t s)))
9319    (or string (setq s (concat "*" s)))  ; Add * for headlines
9320    (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9321
9322(defun org-make-link (&rest strings)
9323  "Concatenate STRINGS, format resulting string with `org-link-format'."
9324  (apply 'concat strings))
9325
9326(defun org-make-link-string (link &optional description)
9327  "Make a link with brackets, consisting of LINK and DESCRIPTION."
9328  (when (stringp description)
9329    ;; Remove brackets from the description, they are fatal.
9330    (while (string-match "\\[\\|\\]" description)
9331      (setq description (replace-match "" t t description))))
9332  (when (equal (org-link-escape link) description)
9333    ;; No description needed, it is identical
9334    (setq description nil))
9335  (when (and (not description)
9336	     (not (equal link (org-link-escape link))))
9337    (setq description link))
9338  (concat "[[" (org-link-escape link) "]"
9339	  (if description (concat "[" description "]") "")
9340	  "]"))
9341
9342(defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
9343  "Association list of escapes for some characters problematic in links.")
9344
9345(defun org-link-escape (text)
9346  "Escape charaters in TEXT that are problematic for links."
9347  (when text
9348    (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
9349			 org-link-escape-chars "\\|")))
9350      (while (string-match re text)
9351	(setq text
9352	      (replace-match
9353	       (cdr (assoc (match-string 0 text) org-link-escape-chars))
9354	       t t text)))
9355      text)))
9356
9357(defun org-link-unescape (text)
9358  "Reverse the action of `org-link-escape'."
9359  (when text
9360    (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
9361			 org-link-escape-chars "\\|")))
9362      (while (string-match re text)
9363	(setq text
9364	      (replace-match
9365	       (car (rassoc (match-string 0 text) org-link-escape-chars))
9366	       t t text)))
9367      text)))
9368
9369(defun org-xor (a b)
9370  "Exclusive or."
9371  (if a (not b) b))
9372
9373(defun org-get-header (header)
9374  "Find a header field in the current buffer."
9375  (save-excursion
9376    (goto-char (point-min))
9377    (let ((case-fold-search t) s)
9378      (cond
9379       ((eq header 'from)
9380	(if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
9381	    (setq s (match-string 1)))
9382	(while (string-match "\"" s)
9383	  (setq s (replace-match "" t t s)))
9384	(if (string-match "[<(].*" s)
9385	    (setq s (replace-match "" t t s))))
9386       ((eq header 'message-id)
9387	(if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
9388	    (setq s (match-string 1))))
9389       ((eq header 'subject)
9390	(if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
9391	    (setq s (match-string 1)))))
9392      (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
9393      (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
9394      s)))
9395
9396
9397(defun org-fixup-message-id-for-http (s)
9398  "Replace special characters in a message id, so it can be used in an http query."
9399  (while (string-match "<" s)
9400    (setq s (replace-match "%3C" t t s)))
9401  (while (string-match ">" s)
9402    (setq s (replace-match "%3E" t t s)))
9403  (while (string-match "@" s)
9404    (setq s (replace-match "%40" t t s)))
9405  s)
9406
9407(defun org-insert-link (&optional complete-file)
9408  "Insert a link.  At the prompt, enter the link.
9409
9410Completion can be used to select a link previously stored with
9411`org-store-link'.  When the empty string is entered (i.e. if you just
9412press RET at the prompt), the link defaults to the most recently
9413stored link.  As SPC triggers completion in the minibuffer, you need to
9414use M-SPC or C-q SPC to force the insertion of a space character.
9415
9416You will also be prompted for a description, and if one is given, it will
9417be displayed in the buffer instead of the link.
9418
9419If there is already a link at point, this command will allow you to edit link
9420and description parts.
9421
9422With a \\[universal-argument] prefix, prompts for a file to link to.  The file name can be
9423selected using completion.  The path to the file will be relative to
9424the current directory if the file is in the current directory or a
9425subdirectory.  Otherwise, the link will be the absolute path as
9426completed in the minibuffer (i.e. normally ~/path/to/file).
9427
9428With two \\[universal-argument] prefixes, enforce an absolute path even if the file
9429is in the current directory or below.
9430With three \\[universal-argument] prefixes, negate the meaning of
9431`org-keep-stored-link-after-insertion'."
9432  (interactive "P")
9433  (let ((region (if (org-region-active-p)
9434		    (prog1 (buffer-substring (region-beginning) (region-end))
9435		      (delete-region (region-beginning) (region-end)))))
9436        tmphist ; byte-compile incorrectly complains about this
9437	link desc entry remove file)
9438    (cond
9439     ((org-in-regexp org-bracket-link-regexp 1)
9440      ;; We do have a link at point, and we are going to edit it.
9441      (setq remove (list (match-beginning 0) (match-end 0)))
9442      (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9443      (setq link (read-string "Link: "
9444			      (org-link-unescape
9445			       (org-match-string-no-properties 1)))))
9446     ((or (org-in-regexp org-angle-link-re)
9447	  (org-in-regexp org-plain-link-re))
9448      ;; Convert to bracket link
9449      (setq remove (list (match-beginning 0) (match-end 0))
9450	    link (read-string "Link: "
9451			      (org-remove-angle-brackets (match-string 0)))))
9452     ((equal complete-file '(4))
9453      ;; Completing read for file names.
9454      (setq file (read-file-name "File: "))
9455      (let ((pwd (file-name-as-directory (expand-file-name ".")))
9456	    (pwd1 (file-name-as-directory (abbreviate-file-name
9457					   (expand-file-name ".")))))
9458	(cond
9459	 ((equal complete-file '(16))
9460	  (setq link (org-make-link
9461		      "file:"
9462		      (abbreviate-file-name (expand-file-name file)))))
9463	 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9464	  (setq link  (org-make-link "file:" (match-string 1 file))))
9465	 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9466			(expand-file-name file))
9467	  (setq link  (org-make-link
9468		       "file:" (match-string 1 (expand-file-name file)))))
9469	 (t (setq link (org-make-link "file:" file))))))
9470     (t
9471      ;; Read link, with completion for stored links.
9472      ;; Fake a link history
9473      (setq tmphist (append (mapcar 'car org-stored-links)
9474			    org-insert-link-history))
9475      (setq link (org-completing-read
9476		  "Link: " org-stored-links nil nil nil
9477		  'tmphist
9478		  (or (car (car org-stored-links)))))
9479      (setq entry (assoc link org-stored-links))
9480      (or entry (push link org-insert-link-history))
9481      (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9482		   (not org-keep-stored-link-after-insertion))
9483	  (setq org-stored-links (delq (assoc link org-stored-links)
9484				       org-stored-links)))
9485      (setq link (if entry (nth 1 entry) link)
9486	    desc (or region desc (nth 2 entry)))))
9487
9488    (if (string-match org-plain-link-re link)
9489	;; URL-like link, normalize the use of angular brackets.
9490	(setq link (org-make-link (org-remove-angle-brackets link))))
9491
9492    ;; Check if we are linking to the current file with a search option
9493    ;; If yes, simplify the link by using only the search option.
9494    (when (and buffer-file-name
9495	       (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
9496      (let* ((path (match-string 1 link))
9497	     (case-fold-search nil)
9498	     (search (match-string 2 link)))
9499	(save-match-data
9500	  (if (equal (file-truename buffer-file-name) (file-truename path))
9501	      ;; We are linking to this same file, with a search option
9502	      (setq link search)))))
9503
9504    ;; Check if we can/should use a relative path.  If yes, simplify the link
9505    (when (string-match "\\<file:\\(.*\\)" link)
9506      (let* ((path (match-string 1 link))
9507	     (case-fold-search nil))
9508	(cond
9509	 ((eq org-link-file-path-type 'absolute)
9510	  (setq path (abbreviate-file-name (expand-file-name path))))
9511	 ((eq org-link-file-path-type 'noabbrev)
9512	  (setq path (expand-file-name path)))
9513	 ((eq org-link-file-path-type 'relative)
9514	  (setq path (file-relative-name path)))
9515	 (t
9516	  (save-match-data
9517	    (if (string-match (concat "^" (regexp-quote
9518					   (file-name-as-directory
9519					    (expand-file-name "."))))
9520			      (expand-file-name path))
9521		;; We are linking a file with relative path name.
9522		(setq path (substring (expand-file-name path)
9523				      (match-end 0)))))))
9524	(setq link (concat "file:" path))))
9525
9526    (setq desc (read-string "Description: " desc))
9527    (unless (string-match "\\S-" desc) (setq desc nil))
9528    (if remove (apply 'delete-region remove))
9529    (insert (org-make-link-string link desc))))
9530
9531(defun org-completing-read (&rest args)
9532  (let ((minibuffer-local-completion-map
9533	 (copy-keymap minibuffer-local-completion-map)))
9534    (define-key minibuffer-local-completion-map " " 'self-insert-command)
9535    (apply 'completing-read args)))
9536
9537;;; Opening/following a link
9538(defvar org-link-search-failed nil)
9539
9540(defun org-next-link ()
9541  "Move forward to the next link.
9542If the link is in hidden text, expose it."
9543  (interactive)
9544  (when (and org-link-search-failed (eq this-command last-command))
9545    (goto-char (point-min))
9546    (message "Link search wrapped back to beginning of buffer"))
9547  (setq org-link-search-failed nil)
9548  (let* ((pos (point))
9549	 (ct (org-context))
9550	 (a (assoc :link ct)))
9551    (if a (goto-char (nth 2 a)))
9552    (if (re-search-forward org-any-link-re nil t)
9553	(progn
9554	  (goto-char (match-beginning 0))
9555	  (if (org-invisible-p) (org-show-context)))
9556      (goto-char pos)
9557      (setq org-link-search-failed t)
9558      (error "No further link found"))))
9559
9560(defun org-previous-link ()
9561  "Move backward to the previous link.
9562If the link is in hidden text, expose it."
9563  (interactive)
9564  (when (and org-link-search-failed (eq this-command last-command))
9565    (goto-char (point-max))
9566    (message "Link search wrapped back to end of buffer"))
9567  (setq org-link-search-failed nil)
9568  (let* ((pos (point))
9569	 (ct (org-context))
9570	 (a (assoc :link ct)))
9571    (if a (goto-char (nth 1 a)))
9572    (if (re-search-backward org-any-link-re nil t)
9573	(progn
9574	  (goto-char (match-beginning 0))
9575	  (if (org-invisible-p) (org-show-context)))
9576      (goto-char pos)
9577      (setq org-link-search-failed t)
9578      (error "No further link found"))))
9579
9580(defun org-find-file-at-mouse (ev)
9581  "Open file link or URL at mouse."
9582  (interactive "e")
9583  (mouse-set-point ev)
9584  (org-open-at-point 'in-emacs))
9585
9586(defun org-open-at-mouse (ev)
9587  "Open file link or URL at mouse."
9588  (interactive "e")
9589  (mouse-set-point ev)
9590  (org-open-at-point))
9591
9592(defvar org-window-config-before-follow-link nil
9593  "The window configuration before following a link.
9594This is saved in case the need arises to restore it.")
9595
9596(defvar org-open-link-marker (make-marker)
9597  "Marker pointing to the location where `org-open-at-point; was called.")
9598
9599(defun org-open-at-point (&optional in-emacs)
9600  "Open link at or after point.
9601If there is no link at point, this function will search forward up to
9602the end of the current subtree.
9603Normally, files will be opened by an appropriate application.  If the
9604optional argument IN-EMACS is non-nil, Emacs will visit the file."
9605  (interactive "P")
9606  (move-marker org-open-link-marker (point))
9607  (setq org-window-config-before-follow-link (current-window-configuration))
9608  (org-remove-occur-highlights nil nil t)
9609  (if (org-at-timestamp-p t)
9610      (org-follow-timestamp-link)
9611    (let (type path link line search (pos (point)))
9612      (catch 'match
9613	(save-excursion
9614	  (skip-chars-forward "^]\n\r")
9615	  (when (org-in-regexp org-bracket-link-regexp)
9616	    (setq link (org-link-unescape (org-match-string-no-properties 1)))
9617	    (while (string-match " *\n *" link)
9618	      (setq link (replace-match " " t t link)))
9619	    (setq link (org-link-expand-abbrev link))
9620	    (if (string-match org-link-re-with-space2 link)
9621		(setq type (match-string 1 link) path (match-string 2 link))
9622	      (setq type "thisfile" path link))
9623	    (throw 'match t)))
9624
9625	(when (get-text-property (point) 'org-linked-text)
9626	  (setq type "thisfile"
9627		pos (if (get-text-property (1+ (point)) 'org-linked-text)
9628			(1+ (point)) (point))
9629		path (buffer-substring
9630		      (previous-single-property-change pos 'org-linked-text)
9631		      (next-single-property-change pos 'org-linked-text)))
9632	  (throw 'match t))
9633
9634	(save-excursion
9635	  (when (or (org-in-regexp org-angle-link-re)
9636		    (org-in-regexp org-plain-link-re))
9637	    (setq type (match-string 1) path (match-string 2))
9638	    (throw 'match t)))
9639	(save-excursion
9640	  (when (org-in-regexp "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
9641	    (setq type "tags"
9642		  path (match-string 1))
9643	    (while (string-match ":" path)
9644	      (setq path (replace-match "+" t t path)))
9645	    (throw 'match t))))
9646      (unless path
9647	(error "No link found"))
9648      ;; Remove any trailing spaces in path
9649      (if (string-match " +\\'" path)
9650	  (setq path (replace-match "" t t path)))
9651
9652      (cond
9653
9654       ((equal type "mailto")
9655	(let ((cmd (car org-link-mailto-program))
9656	      (args (cdr org-link-mailto-program)) args1
9657	      (address path) (subject "") a)
9658	  (if (string-match "\\(.*\\)::\\(.*\\)" path)
9659	      (setq address (match-string 1 path)
9660		    subject (org-link-escape (match-string 2 path))))
9661	  (while args
9662	    (cond
9663	     ((not (stringp (car args))) (push (pop args) args1))
9664	     (t (setq a (pop args))
9665		(if (string-match "%a" a)
9666		    (setq a (replace-match address t t a)))
9667		(if (string-match "%s" a)
9668		    (setq a (replace-match subject t t a)))
9669		(push a args1))))
9670	  (apply cmd (nreverse args1))))
9671
9672       ((member type '("http" "https" "ftp" "news"))
9673	(browse-url (concat type ":" path)))
9674
9675       ((string= type "tags")
9676	(org-tags-view in-emacs path))
9677       ((string= type "thisfile")
9678	(if in-emacs
9679	    (switch-to-buffer-other-window
9680	     (org-get-buffer-for-internal-link (current-buffer)))
9681	  (org-mark-ring-push))
9682	(org-link-search
9683	 path
9684	 (cond ((equal in-emacs '(4)) 'occur)
9685	       ((equal in-emacs '(16)) 'org-occur)
9686	       (t nil))
9687	 pos))
9688
9689       ((string= type "file")
9690	(if (string-match "::\\([0-9]+\\)\\'" path)
9691	    (setq line (string-to-number (match-string 1 path))
9692		  path (substring path 0 (match-beginning 0)))
9693	  (if (string-match "::\\(.+\\)\\'" path)
9694	      (setq search (match-string 1 path)
9695		    path (substring path 0 (match-beginning 0)))))
9696	(org-open-file path in-emacs line search))
9697
9698       ((string= type "news")
9699	(org-follow-gnus-link path))
9700
9701       ((string= type "bbdb")
9702	(org-follow-bbdb-link path))
9703
9704       ((string= type "info")
9705	(org-follow-info-link path))
9706
9707       ((string= type "gnus")
9708	(let (group article)
9709	  (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9710	      (error "Error in Gnus link"))
9711	  (setq group (match-string 1 path)
9712		article (match-string 3 path))
9713	  (org-follow-gnus-link group article)))
9714
9715       ((string= type "vm")
9716	(let (folder article)
9717	  (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9718	      (error "Error in VM link"))
9719	  (setq folder (match-string 1 path)
9720		article (match-string 3 path))
9721	  ;; in-emacs is the prefix arg, will be interpreted as read-only
9722	  (org-follow-vm-link folder article in-emacs)))
9723
9724       ((string= type "wl")
9725	(let (folder article)
9726	  (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9727	      (error "Error in Wanderlust link"))
9728	  (setq folder (match-string 1 path)
9729		article (match-string 3 path))
9730	  (org-follow-wl-link folder article)))
9731
9732       ((string= type "mhe")
9733	(let (folder article)
9734	  (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9735	      (error "Error in MHE link"))
9736	  (setq folder (match-string 1 path)
9737		article (match-string 3 path))
9738	  (org-follow-mhe-link folder article)))
9739
9740       ((string= type "rmail")
9741	(let (folder article)
9742	  (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9743	      (error "Error in RMAIL link"))
9744	  (setq folder (match-string 1 path)
9745		article (match-string 3 path))
9746	  (org-follow-rmail-link folder article)))
9747
9748       ((string= type "shell")
9749	(let ((cmd path))
9750	  ;; FIXME: the following is only for backward compatibility
9751	  (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
9752	  (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
9753	  (if (or (not org-confirm-shell-link-function)
9754		  (funcall org-confirm-shell-link-function
9755			   (format "Execute \"%s\" in shell? "
9756				   (org-add-props cmd nil
9757				     'face 'org-warning))))
9758	      (progn
9759		(message "Executing %s" cmd)
9760		(shell-command cmd))
9761	    (error "Abort"))))
9762
9763       ((string= type "elisp")
9764	(let ((cmd path))
9765	  (if (or (not org-confirm-elisp-link-function)
9766		  (funcall org-confirm-elisp-link-function
9767			   (format "Execute \"%s\" as elisp? "
9768				   (org-add-props cmd nil
9769						  'face 'org-warning))))
9770              (message "%s => %s" cmd (eval (read cmd)))
9771	    (error "Abort"))))
9772
9773       (t
9774	(browse-url-at-point)))))
9775  (move-marker org-open-link-marker nil))
9776
9777
9778;;; File search
9779
9780(defvar org-create-file-search-functions nil
9781  "List of functions to construct the right search string for a file link.
9782These functions are called in turn with point at the location to
9783which the link should point.
9784
9785A function in the hook should first test if it would like to
9786handle this file type, for example by checking the major-mode or
9787the file extension.  If it decides not to handle this file, it
9788should just return nil to give other functions a chance.  If it
9789does handle the file, it must return the search string to be used
9790when following the link.  The search string will be part of the
9791file link, given after a double colon, and `org-open-at-point'
9792will automatically search for it.  If special measures must be
9793taken to make the search successful, another function should be
9794added to the companion hook `org-execute-file-search-functions',
9795which see.
9796
9797A function in this hook may also use `setq' to set the variable
9798`description' to provide a suggestion for the descriptive text to
9799be used for this link when it gets inserted into an Org-mode
9800buffer with \\[org-insert-link].")
9801
9802(defvar org-execute-file-search-functions nil
9803  "List of functions to execute a file search triggered by a link.
9804
9805Functions added to this hook must accept a single argument, the
9806search string that was part of the file link, the part after the
9807double colon.  The function must first check if it would like to
9808handle this search, for example by checking the major-mode or the
9809file extension.  If it decides not to handle this search, it
9810should just return nil to give other functions a chance.  If it
9811does handle the search, it must return a non-nil value to keep
9812other functions from trying.
9813
9814Each function can access the current prefix argument through the
9815variable `current-prefix-argument'.  Note that a single prefix is
9816used to force opening a link in Emacs, so it may be good to only
9817use a numeric or double prefix to guide the search function.
9818
9819In case this is needed, a function in this hook can also restore
9820the window configuration before `org-open-at-point' was called using:
9821
9822    (set-window-configuration org-window-config-before-follow-link)")
9823
9824(defun org-link-search (s &optional type avoid-pos)
9825  "Search for a link search option.
9826If S is surrounded by forward slashes, it is interpreted as a
9827regular expression.  In org-mode files, this will create an `org-occur'
9828sparse tree.  In ordinary files, `occur' will be used to list matches.
9829If the current buffer is in `dired-mode', grep will be used to search
9830in all files.  If AVOID-POS is given, ignore matches near that position."
9831  (let ((case-fold-search t)
9832	(s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9833	(pos (point))
9834	(pre "") (post "")
9835	words re0 re1 re2 re3 re4 re5 re2a reall)
9836    (cond
9837     ;; First check if there are any special
9838     ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9839     ;; Now try the builtin stuff
9840     ((save-excursion
9841	(goto-char (point-min))
9842	(and
9843	 (re-search-forward
9844	  (concat "<<" (regexp-quote s0) ">>") nil t)
9845	 (setq pos (match-beginning 0))))
9846      ;; There is an exact target for this
9847      (goto-char pos))
9848     ((string-match "^/\\(.*\\)/$" s)
9849      ;; A regular expression
9850      (cond
9851       ((org-mode-p)
9852	(org-occur (match-string 1 s)))
9853       ;;((eq major-mode 'dired-mode)
9854       ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9855       (t (org-do-occur (match-string 1 s)))))
9856     (t
9857      ;; A normal search string
9858      (when (equal (string-to-char s) ?*)
9859	;; Anchor on headlines, post may include tags.
9860	(setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
9861	      post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
9862	      s (substring s 1)))
9863      (remove-text-properties
9864       0 (length s)
9865       '(face nil mouse-face nil keymap nil fontified nil) s)
9866      ;; Make a series of regular expressions to find a match
9867      (setq words (org-split-string s "[ \n\r\t]+")
9868	    re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9869	    re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
9870	    re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9871	    re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9872	    re1 (concat pre re2 post)
9873	    re3 (concat pre re4 post)
9874	    re5 (concat pre ".*" re4)
9875	    re2 (concat pre re2)
9876	    re2a (concat pre re2a)
9877	    re4 (concat pre re4)
9878	    reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9879			  "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9880			  re5 "\\)"
9881			  ))
9882      (cond
9883       ((eq type 'org-occur) (org-occur reall))
9884       ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9885       (t (goto-char (point-min))
9886	  (if (or (org-search-not-self 1 re0 nil t)
9887		  (org-search-not-self 1 re1 nil t)
9888		  (org-search-not-self 1 re2 nil t)
9889		  (org-search-not-self 1 re2a nil t)
9890		  (org-search-not-self 1 re3 nil t)
9891		  (org-search-not-self 1 re4 nil t)
9892		  (org-search-not-self 1 re5 nil t)
9893		  )
9894	      (goto-char (match-beginning 1))
9895	    (goto-char pos)
9896	    (error "No match")))))
9897     (t
9898      ;; Normal string-search
9899      (goto-char (point-min))
9900      (if (search-forward s nil t)
9901	  (goto-char (match-beginning 0))
9902	(error "No match"))))
9903    (and (org-mode-p) (org-show-context 'link-search))))
9904
9905(defun org-search-not-self (group &rest args)
9906  "Execute `re-search-forward', but only accept matches that do not
9907enclose the position of `org-open-link-marker'."
9908  (let ((m org-open-link-marker))
9909    (catch 'exit
9910      (while (apply 're-search-forward args)
9911	(goto-char (match-end group))
9912	(if (and (or (not (eq (marker-buffer m) (current-buffer)))
9913		     (> (match-beginning 0) (marker-position m))
9914		     (< (match-end 0) (marker-position m)))
9915		 (save-match-data
9916		   (or (not (org-in-regexp org-bracket-link-analytic-regexp 1))
9917		       (not (match-end 4))  ; no description
9918		       (and (<= (match-beginning 4) (point))
9919			    (>= (match-end 4) (point))))))
9920		 (throw 'exit (point)))))))
9921
9922(defun org-get-buffer-for-internal-link (buffer)
9923  "Return a buffer to be used for displaying the link target of internal links."
9924  (cond
9925   ((not org-display-internal-link-with-indirect-buffer)
9926    buffer)
9927   ((string-match "(Clone)$" (buffer-name buffer))
9928    (message "Buffer is already a clone, not making another one")
9929    ;; we also do not modify visibility in this case
9930    buffer)
9931   (t ; make a new indirect buffer for displaying the link
9932    (let* ((bn (buffer-name buffer))
9933	   (ibn (concat bn "(Clone)"))
9934	   (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9935      (with-current-buffer ib (org-overview))
9936      ib))))
9937
9938(defun org-do-occur (regexp &optional cleanup)
9939  "Call the Emacs command `occur'.
9940If CLEANUP is non-nil, remove the printout of the regular expression
9941in the *Occur* buffer.  This is useful if the regex is long and not useful
9942to read."
9943  (occur regexp)
9944  (when cleanup
9945    (let ((cwin (selected-window)) win beg end)
9946      (when (setq win (get-buffer-window "*Occur*"))
9947	(select-window win))
9948      (goto-char (point-min))
9949      (when (re-search-forward "match[a-z]+" nil t)
9950	(setq beg (match-end 0))
9951	(if (re-search-forward "^[ \t]*[0-9]+" nil t)
9952	    (setq end (1- (match-beginning 0)))))
9953      (and beg end (let ((buffer-read-only)) (delete-region beg end)))
9954      (goto-char (point-min))
9955      (select-window cwin))))
9956
9957;;; The mark ring for links jumps
9958
9959(defvar org-mark-ring nil
9960  "Mark ring for positions before jumps in Org-mode.")
9961(defvar org-mark-ring-last-goto nil
9962  "Last position in the mark ring used to go back.")
9963;; Fill and close the ring
9964(setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9965(loop for i from 1 to org-mark-ring-length do
9966      (push (make-marker) org-mark-ring))
9967(setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9968	org-mark-ring)
9969
9970(defun org-mark-ring-push (&optional pos buffer)
9971  "Put the current position or POS into the mark ring and rotate it."
9972  (interactive)
9973  (setq pos (or pos (point)))
9974  (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9975  (move-marker (car org-mark-ring)
9976	       (or pos (point))
9977	       (or buffer (current-buffer)))
9978  (message
9979   (substitute-command-keys
9980    "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9981
9982(defun org-mark-ring-goto (&optional n)
9983  "Jump to the previous position in the mark ring.
9984With prefix arg N, jump back that many stored positions.  When
9985called several times in succession, walk through the entire ring.
9986Org-mode commands jumping to a different position in the current file,
9987or to another Org-mode file, automatically push the old position
9988onto the ring."
9989  (interactive "p")
9990  (let (p m)
9991    (if (eq last-command this-command)
9992	(setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9993      (setq p org-mark-ring))
9994    (setq org-mark-ring-last-goto p)
9995    (setq m (car p))
9996    (switch-to-buffer (marker-buffer m))
9997    (goto-char m)
9998    (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9999
10000(defun org-remove-angle-brackets (s)
10001  (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10002  (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10003  s)
10004(defun org-add-angle-brackets (s)
10005  (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10006  (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10007  s)
10008
10009;;; Following specific links
10010
10011(defun org-follow-timestamp-link ()
10012  (cond
10013   ((org-at-date-range-p t)
10014    (let ((org-agenda-start-on-weekday)
10015	  (t1 (match-string 1))
10016	  (t2 (match-string 2)))
10017      (setq t1 (time-to-days (org-time-string-to-time t1))
10018	    t2 (time-to-days (org-time-string-to-time t2)))
10019      (org-agenda-list nil t1 (1+ (- t2 t1)))))
10020   ((org-at-timestamp-p t)
10021    (org-agenda-list nil (time-to-days (org-time-string-to-time
10022					(substring (match-string 1) 0 10)))
10023		     1))
10024   (t (error "This should not happen"))))
10025
10026
10027(defun org-follow-bbdb-link (name)
10028  "Follow a BBDB link to NAME."
10029  (require 'bbdb)
10030  (let ((inhibit-redisplay (not debug-on-error))
10031	(bbdb-electric-p nil))
10032    (catch 'exit
10033      ;; Exact match on name
10034      (bbdb-name (concat "\\`" name "\\'") nil)
10035      (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10036      ;; Exact match on name
10037      (bbdb-company (concat "\\`" name "\\'") nil)
10038      (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10039      ;; Partial match on name
10040      (bbdb-name name nil)
10041      (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10042      ;; Partial match on company
10043      (bbdb-company name nil)
10044      (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10045      ;; General match including network address and notes
10046      (bbdb name nil)
10047      (when (= 0 (buffer-size (get-buffer "*BBDB*")))
10048	(delete-window (get-buffer-window "*BBDB*"))
10049	(error "No matching BBDB record")))))
10050
10051(defun org-follow-info-link (name)
10052  "Follow an info file & node link  to NAME."
10053  (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
10054          (string-match "\\(.*\\)" name))
10055      (progn
10056	(require 'info)
10057        (if (match-string 2 name) ; If there isn't a node, choose "Top"
10058            (Info-find-node (match-string 1 name) (match-string 2 name))
10059          (Info-find-node (match-string 1 name) "Top")))
10060    (message (concat "Could not open: " name))))
10061
10062(defun org-follow-gnus-link (&optional group article)
10063  "Follow a Gnus link to GROUP and ARTICLE."
10064  (require 'gnus)
10065  (funcall (cdr (assq 'gnus org-link-frame-setup)))
10066  (if gnus-other-frame-object (select-frame gnus-other-frame-object))
10067  (cond ((and group article)
10068	 (gnus-group-read-group 0 nil group)
10069	 (gnus-summary-goto-article (string-to-number article) nil t))
10070	(group (gnus-group-jump-to-group group))))
10071
10072(defun org-follow-vm-link (&optional folder article readonly)
10073  "Follow a VM link to FOLDER and ARTICLE."
10074  (require 'vm)
10075  (setq article (org-add-angle-brackets article))
10076  (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
10077      ;; ange-ftp or efs or tramp access
10078      (let ((user (or (match-string 1 folder) (user-login-name)))
10079	    (host (match-string 2 folder))
10080	    (file (match-string 3 folder)))
10081	(cond
10082	 ((featurep 'tramp)
10083	  ;; use tramp to access the file
10084	  (if (featurep 'xemacs)
10085	      (setq folder (format "[%s@%s]%s" user host file))
10086	    (setq folder (format "/%s@%s:%s" user host file))))
10087	 (t
10088	  ;; use ange-ftp or efs
10089	  (require (if (featurep 'xemacs) 'efs 'ange-ftp))
10090	  (setq folder (format "/%s@%s:%s" user host file))))))
10091  (when folder
10092    (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
10093    (sit-for 0.1)
10094    (when article
10095      (vm-select-folder-buffer)
10096      (widen)
10097      (let ((case-fold-search t))
10098	(goto-char (point-min))
10099	(if (not (re-search-forward
10100		  (concat "^" "message-id: *" (regexp-quote article))))
10101	    (error "Could not find the specified message in this folder"))
10102	(vm-isearch-update)
10103	(vm-isearch-narrow)
10104	(vm-beginning-of-message)
10105	(vm-summarize)))))
10106
10107(defun org-follow-wl-link (folder article)
10108  "Follow a Wanderlust link to FOLDER and ARTICLE."
10109  (if (and (string= folder "%")
10110	   article
10111	   (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
10112      ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
10113      ;; Thus, we recompose folder and article ids.
10114      (setq folder (format "%s#%s" folder (match-string 1 article))
10115	    article (match-string 3 article)))
10116  (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
10117      (error "No such folder: %s" folder))
10118  (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
10119  (and article
10120       (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
10121       (wl-summary-redisplay)))
10122
10123(defun org-follow-rmail-link (folder article)
10124  "Follow an RMAIL link to FOLDER and ARTICLE."
10125  (setq article (org-add-angle-brackets article))
10126  (let (message-number)
10127    (save-excursion
10128      (save-window-excursion
10129	(rmail (if (string= folder "RMAIL") rmail-file-name folder))
10130	(setq message-number
10131	      (save-restriction
10132		(widen)
10133		(goto-char (point-max))
10134		(if (re-search-backward
10135		     (concat "^Message-ID:\\s-+" (regexp-quote
10136						  (or article "")))
10137		     nil t)
10138		    (rmail-what-message))))))
10139    (if message-number
10140	(progn
10141	  (rmail (if (string= folder "RMAIL") rmail-file-name folder))
10142	  (rmail-show-message message-number)
10143	  message-number)
10144      (error "Message not found"))))
10145
10146;;; mh-e integration based on planner-mode
10147(defun org-mhe-get-message-real-folder ()
10148  "Return the name of the current message real folder, so if you use
10149sequences, it will now work."
10150  (save-excursion
10151    (let* ((folder
10152            (if (equal major-mode 'mh-folder-mode)
10153                mh-current-folder
10154              ;; Refer to the show buffer
10155              mh-show-folder-buffer))
10156           (end-index
10157            (if (boundp 'mh-index-folder)
10158                (min (length mh-index-folder) (length folder))))
10159           )
10160      ;; a simple test on mh-index-data does not work, because
10161      ;; mh-index-data is always nil in a show buffer.
10162      (if (and (boundp 'mh-index-folder)
10163               (string= mh-index-folder (substring folder 0 end-index)))
10164          (if (equal major-mode 'mh-show-mode)
10165              (save-window-excursion
10166                (when (buffer-live-p (get-buffer folder))
10167                  (progn
10168                    (pop-to-buffer folder)
10169                    (org-mhe-get-message-folder-from-index)
10170                    )
10171                  ))
10172            (org-mhe-get-message-folder-from-index)
10173            )
10174        folder
10175        )
10176      )))
10177
10178(defun org-mhe-get-message-folder-from-index ()
10179  "Returns the name of the message folder in a index folder buffer."
10180  (save-excursion
10181    (mh-index-previous-folder)
10182    (re-search-forward "^\\(+.*\\)$" nil t)
10183    (message (match-string 1))))
10184
10185(defun org-mhe-get-message-folder ()
10186  "Return the name of the current message folder.  Be careful if you
10187use sequences."
10188  (save-excursion
10189    (if (equal major-mode 'mh-folder-mode)
10190        mh-current-folder
10191      ;; Refer to the show buffer
10192      mh-show-folder-buffer)))
10193
10194(defun org-mhe-get-message-num ()
10195  "Return the number of the current message.  Be careful if you
10196use sequences."
10197  (save-excursion
10198    (if (equal major-mode 'mh-folder-mode)
10199        (mh-get-msg-num nil)
10200      ;; Refer to the show buffer
10201      (mh-show-buffer-message-number))))
10202
10203(defun org-mhe-get-header (header)
10204  "Return a header of the message in folder mode. This will create a
10205show buffer for the corresponding message. If you have a more clever
10206idea..."
10207  (let* ((folder (org-mhe-get-message-folder))
10208         (num (org-mhe-get-message-num))
10209         (buffer (get-buffer-create (concat "show-" folder)))
10210         (header-field))
10211  (with-current-buffer buffer
10212    (mh-display-msg num folder)
10213    (if (equal major-mode 'mh-folder-mode)
10214        (mh-header-display)
10215      (mh-show-header-display))
10216    (set-buffer buffer)
10217    (setq header-field (mh-get-header-field header))
10218    (if (equal major-mode 'mh-folder-mode)
10219        (mh-show)
10220      (mh-show-show))
10221    header-field)))
10222
10223(defun org-follow-mhe-link (folder article)
10224  "Follow an MHE link to FOLDER and ARTICLE.
10225If ARTICLE is nil FOLDER is shown.  If the configuration variable
10226`org-mhe-search-all-folders' is t and `mh-searcher' is pick,
10227ARTICLE is searched in all folders.  Indexed searches (swish++,
10228namazu, and others supported by MH-E) will always search in all
10229folders."
10230  (require 'mh-e)
10231  (require 'mh-search)
10232  (require 'mh-utils)
10233  (mh-find-path)
10234  (if (not article)
10235      (mh-visit-folder (mh-normalize-folder-name folder))
10236    (setq article (org-add-angle-brackets article))
10237    (mh-search-choose)
10238    (if (equal mh-searcher 'pick)
10239        (progn
10240          (mh-search folder (list "--message-id" article))
10241          (when (and org-mhe-search-all-folders
10242                     (not (org-mhe-get-message-real-folder)))
10243            (kill-this-buffer)
10244            (mh-search "+" (list "--message-id" article))))
10245      (mh-search "+" article))
10246    (if (org-mhe-get-message-real-folder)
10247        (mh-show-msg 1)
10248      (kill-this-buffer)
10249      (error "Message not found"))))
10250
10251;;; BibTeX links
10252
10253;; Use the custom search meachnism to construct and use search strings for
10254;; file links to BibTeX database entries.
10255
10256(defun org-create-file-search-in-bibtex ()
10257  "Create the search string and description for a BibTeX database entry."
10258  (when (eq major-mode 'bibtex-mode)
10259    ;; yes, we want to construct this search string.
10260    ;; Make a good description for this entry, using names, year and the title
10261    ;; Put it into the `description' variable which is dynamically scoped.
10262    (let ((bibtex-autokey-names 1)
10263	  (bibtex-autokey-names-stretch 1)
10264	  (bibtex-autokey-name-case-convert-function 'identity)
10265	  (bibtex-autokey-name-separator " & ")
10266	  (bibtex-autokey-additional-names " et al.")
10267	  (bibtex-autokey-year-length 4)
10268	  (bibtex-autokey-name-year-separator " ")
10269	  (bibtex-autokey-titlewords 3)
10270	  (bibtex-autokey-titleword-separator " ")
10271	  (bibtex-autokey-titleword-case-convert-function 'identity)
10272	  (bibtex-autokey-titleword-length 'infty)
10273	  (bibtex-autokey-year-title-separator ": "))
10274      (setq description (bibtex-generate-autokey)))
10275    ;; Now parse the entry, get the key and return it.
10276    (save-excursion
10277      (bibtex-beginning-of-entry)
10278      (cdr (assoc "=key=" (bibtex-parse-entry))))))
10279
10280(defun org-execute-file-search-in-bibtex (s)
10281  "Find the link search string S as a key for a database entry."
10282  (when (eq major-mode 'bibtex-mode)
10283    ;; Yes, we want to do the search in this file.
10284    ;; We construct a regexp that searches for "@entrytype{" followed by the key
10285    (goto-char (point-min))
10286    (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
10287				    (regexp-quote s) "[ \t\n]*,") nil t)
10288	 (goto-char (match-beginning 0)))
10289    (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
10290	;; Use double prefix to indicate that any web link should be browsed
10291	(let ((b (current-buffer)) (p (point)))
10292	  ;; Restore the window configuration because we just use the web link
10293	  (set-window-configuration org-window-config-before-follow-link)
10294	  (save-excursion (set-buffer b) (goto-char p)
10295	    (bibtex-url)))
10296      (recenter 0))  ; Move entry start to beginning of window
10297  ;; return t to indicate that the search is done.
10298    t))
10299
10300;; Finally add the functions to the right hooks.
10301(add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
10302(add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
10303
10304;; end of Bibtex link setup
10305
10306;;; Following file links
10307
10308(defun org-open-file (path &optional in-emacs line search)
10309  "Open the file at PATH.
10310First, this expands any special file name abbreviations.  Then the
10311configuration variable `org-file-apps' is checked if it contains an
10312entry for this file type, and if yes, the corresponding command is launched.
10313If no application is found, Emacs simply visits the file.
10314With optional argument IN-EMACS, Emacs will visit the file.
10315Optional LINE specifies a line to go to, optional SEARCH a string to
10316search for.  If LINE or SEARCH is given, the file will always be
10317opened in Emacs.
10318If the file does not exist, an error is thrown."
10319  (setq in-emacs (or in-emacs line search))
10320  (let* ((file (if (equal path "")
10321		   buffer-file-name
10322		 (substitute-in-file-name (expand-file-name path))))
10323	 (apps (append org-file-apps (org-default-apps)))
10324	 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10325	 (dirp (if remp nil (file-directory-p file)))
10326	 (dfile (downcase file))
10327	 (old-buffer (current-buffer))
10328	 (old-pos (point))
10329	 (old-mode major-mode)
10330	 ext cmd)
10331    (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10332	(setq ext (match-string 1 dfile))
10333      (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10334	  (setq ext (match-string 1 dfile))))
10335    (if in-emacs
10336	(setq cmd 'emacs)
10337      (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10338		    (and dirp (cdr (assoc 'directory apps)))
10339		    (cdr (assoc ext apps))
10340		    (cdr (assoc t apps)))))
10341    (when (eq cmd 'mailcap)
10342      (require 'mailcap)
10343      (mailcap-parse-mailcaps)
10344      (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10345	     (command (mailcap-mime-info mime-type)))
10346	(if (stringp command)
10347	    (setq cmd command)
10348	  (setq cmd 'emacs))))
10349    (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
10350	     (not (file-exists-p file))
10351	     (not org-open-non-existing-files))
10352	(error "No such file: %s" file))
10353    (cond
10354     ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10355      ;; Remove quotes around the file name - we'll use shell-quote-argument.
10356      (if (string-match "['\"]%s['\"]" cmd)
10357	  (setq cmd (replace-match "%s" t t cmd)))
10358      (setq cmd (format cmd (shell-quote-argument file)))
10359      (save-window-excursion
10360	(shell-command (concat cmd " &"))))
10361     ((or (stringp cmd)
10362	  (eq cmd 'emacs))
10363      (funcall (cdr (assq 'file org-link-frame-setup)) file)
10364      (if line (goto-line line)
10365	(if search (org-link-search search))))
10366     ((consp cmd)
10367      (eval cmd))
10368     (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10369    (and (org-mode-p) (eq old-mode 'org-mode)
10370	 (or (not (equal old-buffer (current-buffer)))
10371	     (not (equal old-pos (point))))
10372	 (org-mark-ring-push old-pos old-buffer))))
10373
10374(defun org-default-apps ()
10375  "Return the default applications for this operating system."
10376  (cond
10377   ((eq system-type 'darwin)
10378    org-file-apps-defaults-macosx)
10379   ((eq system-type 'windows-nt)
10380    org-file-apps-defaults-windowsnt)
10381   (t org-file-apps-defaults-gnu)))
10382
10383(defun org-expand-file-name (path)
10384  "Replace special path abbreviations and expand the file name."
10385  (expand-file-name path))
10386
10387(defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10388(defun org-file-remote-p (file)
10389  "Test whether FILE specifies a location on a remote system.
10390Return non-nil if the location is indeed remote.
10391
10392For example, the filename \"/user@host:/foo\" specifies a location
10393on the system \"/user@host:\"."
10394  (cond ((fboundp 'file-remote-p)
10395         (file-remote-p file))
10396        ((fboundp 'tramp-handle-file-remote-p)
10397         (tramp-handle-file-remote-p file))
10398        ((and (boundp 'ange-ftp-name-format)
10399              (string-match (car ange-ftp-name-format) file))
10400         t)
10401        (t nil)))
10402
10403
10404;;;; Hooks for remember.el
10405
10406;;;###autoload
10407(defun org-remember-annotation ()
10408  "Return a link to the current location as an annotation for remember.el.
10409If you are using Org-mode files as target for data storage with
10410remember.el, then the annotations should include a link compatible with the
10411conventions in Org-mode.  This function returns such a link."
10412  (org-store-link nil))
10413
10414(defconst org-remember-help
10415"Select a destination location for the note.
10416UP/DOWN=headline   TAB=cycle visibility  [Q]uit   RET/<left>/<right>=Store
10417RET at beg-of-buf -> Append to file as level 2 headline
10418RET on headline   -> Store as sublevel entry to current headline
10419<left>/<right>    -> before/after current headline, same headings level")
10420
10421;;;###autoload
10422(defun org-remember-apply-template (&optional use-char skip-interactive)
10423  "Initialize *remember* buffer with template, invoke `org-mode'.
10424This function should be placed into `remember-mode-hook' and in fact requires
10425to be run from that hook to fucntion properly."
10426  (if org-remember-templates
10427
10428      (let* ((char (or use-char
10429		       (if (= (length org-remember-templates) 1)
10430			   (caar org-remember-templates)
10431			 (message "Select template: %s"
10432				  (mapconcat
10433				   (lambda (x) (char-to-string (car x)))
10434				   org-remember-templates " "))
10435			 (read-char-exclusive))))
10436	     (entry (cdr (assoc char org-remember-templates)))
10437	     (tpl (car entry))
10438	     (plist-p (if org-store-link-plist t nil))
10439	     (file (if (and (nth 1 entry) (stringp (nth 1 entry))
10440			    (string-match "\\S-" (nth 1 entry)))
10441		       (nth 1 entry)
10442		     org-default-notes-file))
10443	     (headline (nth 2 entry))
10444	     (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
10445	     (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
10446	     (v-u (concat "[" (substring v-t 1 -1) "]"))
10447	     (v-U (concat "[" (substring v-T 1 -1) "]"))
10448	     (v-i initial)      ; defined in `remember-mode'
10449	     (v-a (if (equal annotation "[[]]") "" annotation)) ; likewise
10450	     (v-n user-full-name)
10451	     (org-startup-folded nil)
10452	     org-time-was-given x prompt char time)
10453	(setq org-store-link-plist
10454	      (append (list :annotation v-a :initial v-i)))
10455	(unless tpl (setq tpl "")	(message "No template") (ding))
10456	(erase-buffer)
10457	(insert (substitute-command-keys
10458		 (format
10459		  "## `C-c C-c' to file interactively, `C-u C-c C-c' to file directly.
10460## Target file \"%s\", headline \"%s\"
10461## To switch templates, use `\\[org-remember]'.\n\n"
10462		  (abbreviate-file-name (or file org-default-notes-file))
10463		  (or headline ""))))
10464	(insert tpl) (goto-char (point-min))
10465	;; Simple %-escapes
10466	(while (re-search-forward "%\\([tTuUai]\\)" nil t)
10467	  (when (and initial (equal (match-string 0) "%i"))
10468	    (save-match-data
10469	      (let* ((lead (buffer-substring
10470			    (point-at-bol) (match-beginning 0))))
10471		(setq v-i (mapconcat 'identity
10472				     (org-split-string initial "\n")
10473				     (concat "\n" lead))))))
10474	  (replace-match
10475	   (or (eval (intern (concat "v-" (match-string 1)))) "")
10476	   t t))
10477	;; From the property list
10478	(when plist-p
10479	  (goto-char (point-min))
10480	  (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
10481	    (and (setq x (plist-get org-store-link-plist
10482				    (intern (match-string 1))))
10483		 (replace-match x t t))))
10484	;; Turn on org-mode in the remember buffer, set local variables
10485	(org-mode)
10486	(org-set-local 'org-finish-function 'remember-buffer)
10487	(if (and file (string-match "\\S-" file) (not (file-directory-p file)))
10488	    (org-set-local 'org-default-notes-file file))
10489	(if (and headline (stringp headline) (string-match "\\S-" headline))
10490	    (org-set-local 'org-remember-default-headline headline))
10491	;; Interactive template entries
10492	(goto-char (point-min))
10493	(while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([uUtT]\\)?" nil t)
10494	  (setq char (if (match-end 3) (match-string 3))
10495		prompt (if (match-end 2) (match-string 2)))
10496	  (goto-char (match-beginning 0))
10497	  (replace-match "")
10498	  (if char
10499	      (progn
10500		(setq org-time-was-given (equal (upcase char) char))
10501		(setq time (org-read-date (equal (upcase char) "U") t nil
10502					  prompt))
10503		(org-insert-time-stamp time org-time-was-given
10504				       (member char '("u" "U"))))
10505	    (insert (read-string
10506		     (if prompt (concat prompt ": ") "Enter string")))))
10507	(goto-char (point-min))
10508	(if (re-search-forward "%\\?" nil t)
10509	    (replace-match "")
10510	  (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
10511    (org-mode)
10512    (org-set-local 'org-finish-function 'remember-buffer)))
10513
10514;;;###autoload
10515(defun org-remember ()
10516  "Call `remember'.  If this is already a remember buffer, re-apply template.
10517If there is an active region, make sure remember uses it as initial content
10518of the remember buffer."
10519  (interactive)
10520  (if (eq org-finish-function 'remember-buffer)
10521      (progn
10522	(when (< (length org-remember-templates) 2)
10523	  (error "No other template available"))
10524	(erase-buffer)
10525	(let ((annotation (plist-get org-store-link-plist :annotation))
10526	      (initial (plist-get org-store-link-plist :initial)))
10527	  (org-remember-apply-template))
10528	(message "Press C-c C-c to remember data"))
10529    (if (org-region-active-p)
10530	(remember (buffer-substring (point) (mark)))
10531      (call-interactively 'remember))))
10532
10533;;;###autoload
10534(defun org-remember-handler ()
10535  "Store stuff from remember.el into an org file.
10536First prompts for an org file.  If the user just presses return, the value
10537of `org-default-notes-file' is used.
10538Then the command offers the headings tree of the selected file in order to
10539file the text at a specific location.
10540You can either immediately press RET to get the note appended to the
10541file, or you can use vertical cursor motion and visibility cycling (TAB) to
10542find a better place.  Then press RET or <left> or <right> in insert the note.
10543
10544Key      Cursor position   Note gets inserted
10545-----------------------------------------------------------------------------
10546RET      buffer-start      as level 2 heading at end of file
10547RET      on headline       as sublevel of the heading at cursor
10548RET      no heading        at cursor position, level taken from context.
10549			   Or use prefix arg to specify level manually.
10550<left>   on headline       as same level, before current heading
10551<right>  on headline       as same level, after current heading
10552
10553So the fastest way to store the note is to press RET RET to append it to
10554the default file.  This way your current train of thought is not
10555interrupted, in accordance with the principles of remember.el.  But with
10556little extra effort, you can push it directly to the correct location.
10557
10558Before being stored away, the function ensures that the text has a
10559headline, i.e. a first line that starts with a \"*\".  If not, a headline
10560is constructed from the current date and some additional data.
10561
10562If the variable `org-adapt-indentation' is non-nil, the entire text is
10563also indented so that it starts in the same column as the headline
10564\(i.e. after the stars).
10565
10566See also the variable `org-reverse-note-order'."
10567  (goto-char (point-min))
10568  (while (looking-at "^[ \t]*\n\\|^##.*\n")
10569    (replace-match ""))
10570  (catch 'quit
10571    (let* ((txt (buffer-substring (point-min) (point-max)))
10572	   (fastp current-prefix-arg)
10573	   (file (if fastp org-default-notes-file (org-get-org-file)))
10574	   (heading org-remember-default-headline)
10575	   (visiting (org-find-base-buffer-visiting file))
10576	   (org-startup-folded nil)
10577	   (org-startup-align-all-tables nil)
10578	   (org-goto-start-pos 1)
10579	   spos level indent reversed)
10580      ;; Modify text so that it becomes a nice subtree which can be inserted
10581      ;; into an org tree.
10582      (let* ((lines (split-string txt "\n"))
10583	     first)
10584	(setq first (car lines) lines (cdr lines))
10585	(if (string-match "^\\*+" first)
10586	    ;; Is already a headline
10587	    (setq indent nil)
10588	  ;; We need to add a headline:  Use time and first buffer line
10589	  (setq lines (cons first lines)
10590		first (concat "* " (current-time-string)
10591			      " (" (remember-buffer-desc) ")")
10592		indent "  "))
10593	(if (and org-adapt-indentation indent)
10594	    (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
10595	(setq txt (concat first "\n"
10596			  (mapconcat 'identity lines "\n"))))
10597      ;; Find the file
10598      (if (not visiting) (find-file-noselect file))
10599      (with-current-buffer (or visiting (get-file-buffer file))
10600	(save-excursion (and (goto-char (point-min))
10601			     (not (re-search-forward "^\\* " nil t))
10602			     (insert "\n* Notes\n")))
10603	(setq reversed (org-notes-order-reversed-p))
10604	(save-excursion
10605	  (save-restriction
10606	    (widen)
10607
10608	    ;; Find the default location
10609	    (when (and heading (stringp heading) (string-match "\\S-" heading))
10610	      (goto-char (point-min))
10611	      (if (re-search-forward
10612		   (concat "^\\*+[ \t]+" (regexp-quote heading)
10613			   "\\([ \t]+:[@a-zA-Z0-9_:]*\\)?[ \t]*$")
10614		   nil t)
10615		  (setq org-goto-start-pos (match-beginning 0))))
10616
10617	    ;; Ask the User for a location
10618	    (setq spos (if fastp
10619			   org-goto-start-pos
10620			 (org-get-location (current-buffer) org-remember-help)))
10621	    (if (not spos) (throw 'quit nil)) ; return nil to show we did
10622					      ; not handle this note
10623	    (goto-char spos)
10624	    (cond ((and (bobp) (not reversed))
10625		   ;; Put it at the end, one level below level 1
10626		   (save-restriction
10627		     (widen)
10628		     (goto-char (point-max))
10629		     (if (not (bolp)) (newline))
10630		     (org-paste-subtree (org-get-legal-level 1 1) txt)))
10631		  ((and (bobp) reversed)
10632		   ;; Put it at the start, as level 1
10633		   (save-restriction
10634		     (widen)
10635		     (goto-char (point-min))
10636		     (re-search-forward "^\\*" nil t)
10637		     (beginning-of-line 1)
10638		     (org-paste-subtree 1 txt)))
10639		  ((and (org-on-heading-p nil) (not current-prefix-arg))
10640		   ;; Put it below this entry, at the beg/end of the subtree
10641		   (org-back-to-heading t)
10642		   (setq level (funcall outline-level))
10643		   (if reversed
10644		       (outline-end-of-heading)
10645		     (org-end-of-subtree t))
10646		   (if (not (bolp)) (newline))
10647		   (beginning-of-line 1)
10648		   (org-paste-subtree (org-get-legal-level level 1) txt))
10649		  (t
10650		   ;; Put it right there, with automatic level determined by
10651		   ;; org-paste-subtree or from prefix arg
10652		   (org-paste-subtree current-prefix-arg txt)))
10653	    (when remember-save-after-remembering
10654	      (save-buffer)
10655	      (if (not visiting) (kill-buffer (current-buffer)))))))))
10656  t)    ;; return t to indicate that we took care of this note.
10657
10658(defun org-get-org-file ()
10659  "Read a filename, with default directory `org-directory'."
10660  (let ((default (or org-default-notes-file remember-data-file)))
10661    (read-file-name (format "File name [%s]: " default)
10662		    (file-name-as-directory org-directory)
10663		    default)))
10664
10665(defun org-notes-order-reversed-p ()
10666  "Check if the current file should receive notes in reversed order."
10667  (cond
10668   ((not org-reverse-note-order) nil)
10669   ((eq t org-reverse-note-order) t)
10670   ((not (listp org-reverse-note-order)) nil)
10671   (t (catch 'exit
10672	(let  ((all org-reverse-note-order)
10673	       entry)
10674	  (while (setq entry (pop all))
10675	    (if (string-match (car entry) buffer-file-name)
10676		(throw 'exit (cdr entry))))
10677	  nil)))))
10678
10679;;;; Dynamic blocks
10680
10681(defun org-find-dblock (name)
10682  "Find the first dynamic block with name NAME in the buffer.
10683If not found, stay at current position and return nil."
10684  (let (pos)
10685    (save-excursion
10686      (goto-char (point-min))
10687      (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
10688					nil t)
10689		     (match-beginning 0))))
10690    (if pos (goto-char pos))
10691    pos))
10692
10693(defconst org-dblock-start-re
10694  "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10695  "Matches the startline of a dynamic block, with parameters.")
10696
10697(defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
10698  "Matches the end of a dyhamic block.")
10699
10700(defun org-create-dblock (plist)
10701  "Create a dynamic block section, with parameters taken from PLIST.
10702PLIST must containe a :name entry which is used as name of the block."
10703  (unless (bolp) (newline))
10704  (let ((name (plist-get plist :name)))
10705    (insert "#+BEGIN: " name)
10706    (while plist
10707      (if (eq (car plist) :name)
10708	  (setq plist (cddr plist))
10709	(insert " " (prin1-to-string (pop plist)))))
10710    (insert "\n\n#+END:\n")
10711    (beginning-of-line -2)))
10712
10713(defun org-prepare-dblock ()
10714  "Prepare dynamic block for refresh.
10715This empties the block, puts the cursor at the insert position and returns
10716the property list including an extra property :name with the block name."
10717  (unless (looking-at org-dblock-start-re)
10718    (error "Not at a dynamic block"))
10719  (let* ((begdel (1+ (match-end 0)))
10720	 (name (match-string 1))
10721	 (params (append (list :name name)
10722			 (read (concat "(" (match-string 3) ")")))))
10723    (unless (re-search-forward org-dblock-end-re nil t)
10724      (error "Dynamic block not terminated"))
10725    (delete-region begdel (match-beginning 0))
10726    (goto-char begdel)
10727    (open-line 1)
10728    params))
10729
10730(defun org-map-dblocks (&optional command)
10731  "Apply COMMAND to all dynamic blocks in the current buffer.
10732If COMMAND is not given, use `org-update-dblock'."
10733  (let ((cmd (or command 'org-update-dblock))
10734	pos)
10735    (save-excursion
10736      (goto-char (point-min))
10737      (while (re-search-forward org-dblock-start-re nil t)
10738	(goto-char (setq pos (match-beginning 0)))
10739	(condition-case nil
10740	    (funcall cmd)
10741	  (error (message "Error during update of dynamic block")))
10742	(goto-char pos)
10743	(unless (re-search-forward org-dblock-end-re nil t)
10744	  (error "Dynamic block not terminated"))))))
10745
10746(defun org-dblock-update (&optional arg)
10747  "User command for updating dynamic blocks.
10748Update the dynamic block at point.  With prefix ARG, update all dynamic
10749blocks in the buffer."
10750  (interactive "P")
10751  (if arg
10752      (org-update-all-dblocks)
10753    (or (looking-at org-dblock-start-re)
10754	(org-beginning-of-dblock))
10755    (org-update-dblock)))
10756
10757(defun org-update-dblock ()
10758  "Update the dynamic block at point
10759This means to empty the block, parse for parameters and then call
10760the correct writing function."
10761  (let* ((pos (point))
10762	 (params (org-prepare-dblock))
10763	 (name (plist-get params :name))
10764	 (cmd (intern (concat "org-dblock-write:" name))))
10765    (funcall cmd params)
10766    (goto-char pos)))
10767
10768(defun org-beginning-of-dblock ()
10769  "Find the beginning of the dynamic block at point.
10770Error if there is no scuh block at point."
10771  (let ((pos (point))
10772	beg)
10773    (end-of-line 1)
10774    (if (and (re-search-backward org-dblock-start-re nil t)
10775	     (setq beg (match-beginning 0))
10776	     (re-search-forward org-dblock-end-re nil t)
10777	     (> (match-end 0) pos))
10778	(goto-char beg)
10779      (goto-char pos)
10780      (error "Not in a dynamic block"))))
10781
10782(defun org-update-all-dblocks ()
10783  "Update all dynamic blocks in the buffer.
10784This function can be used in a hook."
10785  (when (org-mode-p)
10786    (org-map-dblocks 'org-update-dblock)))
10787
10788
10789;;;; Completion
10790
10791(defun org-complete (&optional arg)
10792  "Perform completion on word at point.
10793At the beginning of a headline, this completes TODO keywords as given in
10794`org-todo-keywords'.
10795If the current word is preceded by a backslash, completes the TeX symbols
10796that are supported for HTML support.
10797If the current word is preceded by \"#+\", completes special words for
10798setting file options.
10799In the line after \"#+STARTUP:, complete valid keywords.\"
10800At all other locations, this simply calls `ispell-complete-word'."
10801  (interactive "P")
10802  (catch 'exit
10803    (let* ((end (point))
10804	   (beg1 (save-excursion
10805		   (skip-chars-backward "a-zA-Z_@0-9")
10806		   (point)))
10807	   (beg (save-excursion
10808		  (skip-chars-backward "a-zA-Z0-9_:$")
10809		  (point)))
10810	   (confirm (lambda (x) (stringp (car x))))
10811	   (searchhead (equal (char-before beg) ?*))
10812	   (tag (equal (char-before beg1) ?:))
10813	   (texp (equal (char-before beg) ?\\))
10814	   (link (equal (char-before beg) ?\[))
10815	   (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
10816					 beg)
10817		       "#+"))
10818	   (startup (string-match "^#\\+STARTUP:.*"
10819				 (buffer-substring (point-at-bol) (point))))
10820	   (completion-ignore-case opt)
10821	   (type nil)
10822	   (tbl nil)
10823	   (table (cond
10824		   (opt
10825		    (setq type :opt)
10826		    (mapcar (lambda (x)
10827			      (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
10828			      (cons (match-string 2 x) (match-string 1 x)))
10829			    (org-split-string (org-get-current-options) "\n")))
10830		   (startup
10831		    (setq type :startup)
10832		    org-startup-options)
10833		   (link (append org-link-abbrev-alist-local
10834				 org-link-abbrev-alist))
10835		   (texp
10836		    (setq type :tex)
10837		    org-html-entities)
10838		   ((string-match "\\`\\*+[ \t]*\\'"
10839				  (buffer-substring (point-at-bol) beg))
10840		    (setq type :todo)
10841		    (mapcar 'list org-todo-keywords))
10842		   (searchhead
10843		    (setq type :searchhead)
10844		    (save-excursion
10845		      (goto-char (point-min))
10846		      (while (re-search-forward org-todo-line-regexp nil t)
10847			(push (list
10848			       (org-make-org-heading-search-string
10849				  (match-string 3) t))
10850			      tbl)))
10851		    tbl)
10852		   (tag (setq type :tag beg beg1)
10853			(or org-tag-alist (org-get-buffer-tags)))
10854		   (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
10855	   (pattern (buffer-substring-no-properties beg end))
10856	   (completion (try-completion pattern table confirm)))
10857      (cond ((eq completion t)
10858	     (if (equal type :opt)
10859		 (insert (substring (cdr (assoc (upcase pattern) table))
10860				    (length pattern)))
10861	       (if (equal type :tag) (insert ":"))))
10862	    ((null completion)
10863	     (message "Can't find completion for \"%s\"" pattern)
10864	     (ding))
10865	    ((not (string= pattern completion))
10866	     (delete-region beg end)
10867	     (if (string-match " +$" completion)
10868		 (setq completion (replace-match "" t t completion)))
10869	     (insert completion)
10870	     (if (get-buffer-window "*Completions*")
10871		 (delete-window (get-buffer-window "*Completions*")))
10872	     (if (assoc completion table)
10873		 (if (eq type :todo) (insert " ")
10874		   (if (eq type :tag) (insert ":"))))
10875	     (if (and (equal type :opt) (assoc completion table))
10876		 (message "%s" (substitute-command-keys
10877				"Press \\[org-complete] again to insert example settings"))))
10878	    (t
10879	     (message "Making completion list...")
10880	     (let ((list (sort (all-completions pattern table confirm)
10881			       'string<)))
10882	       (with-output-to-temp-buffer "*Completions*"
10883		 (condition-case nil
10884		     ;; Protection needed for XEmacs and emacs 21
10885		     (display-completion-list list pattern)
10886		   (error (display-completion-list list)))))
10887	     (message "Making completion list...%s" "done"))))))
10888
10889;;;; TODO, DEADLINE, Comments
10890
10891(defun org-toggle-comment ()
10892  "Change the COMMENT state of an entry."
10893  (interactive)
10894  (save-excursion
10895    (org-back-to-heading)
10896    (if (looking-at (concat outline-regexp
10897			    "\\( +\\<" org-comment-string "\\>\\)"))
10898	(replace-match "" t t nil 1)
10899      (if (looking-at outline-regexp)
10900	  (progn
10901	    (goto-char (match-end 0))
10902	    (insert " " org-comment-string))))))
10903
10904(defvar org-last-todo-state-is-todo nil
10905  "This is non-nil when the last TODO state change led to a TODO state.
10906If the last change removed the TODO tag or switched to DONE, then
10907this is nil.")
10908
10909(defun org-todo (&optional arg)
10910  "Change the TODO state of an item.
10911The state of an item is given by a keyword at the start of the heading,
10912like
10913     *** TODO Write paper
10914     *** DONE Call mom
10915
10916The different keywords are specified in the variable `org-todo-keywords'.
10917By default the available states are \"TODO\" and \"DONE\".
10918So for this example: when the item starts with TODO, it is changed to DONE.
10919When it starts with DONE, the DONE is removed.  And when neither TODO nor
10920DONE are present, add TODO at the beginning of the heading.
10921
10922With C-u prefix arg, use completion to determine the new state.
10923With numeric prefix arg, switch to that state.
10924
10925For calling through lisp, arg is also interpreted in the following way:
10926'none             -> empty state
10927\"\"(empty string)  -> switch to empty state
10928'done             -> switch to DONE
10929\"WAITING\"         -> switch to the specified keyword, but only if it
10930                     really is a member of `org-todo-keywords'."
10931  (interactive "P")
10932  (save-excursion
10933    (org-back-to-heading)
10934    (if (looking-at outline-regexp) (goto-char (match-end 0)))
10935    (or (looking-at (concat " +" org-todo-regexp " *"))
10936	(looking-at " *"))
10937    (let* ((this (match-string 1))
10938	   (last-state (or this ""))
10939	   (completion-ignore-case t)
10940	   (member (member this org-todo-keywords))
10941	   (tail (cdr member))
10942	   (state (cond
10943		   ((equal arg '(4))
10944		    ;; Read a state with completion
10945		    (completing-read "State: " (mapcar (lambda(x) (list x))
10946						       org-todo-keywords)
10947				     nil t))
10948		   ((eq arg 'right)
10949		    (if this
10950			(if tail (car tail) nil)
10951		      (car org-todo-keywords)))
10952		   ((eq arg 'left)
10953		    (if (equal member org-todo-keywords)
10954			nil
10955		      (if this
10956			  (nth (- (length org-todo-keywords) (length tail) 2)
10957			       org-todo-keywords)
10958			org-done-string)))
10959		   (arg
10960		    ;; user requests a specific state
10961		    (cond
10962		     ((equal arg "") nil)
10963		     ((eq arg 'none) nil)
10964		     ((eq arg 'done) (org-last org-todo-keywords))
10965		     ((car (member arg org-todo-keywords)))
10966		     ((nth (1- (prefix-numeric-value arg))
10967			     org-todo-keywords))))
10968		   ((null member) (car org-todo-keywords))
10969		   ((null tail) nil) ;; -> first entry
10970		   ((eq org-todo-interpretation 'sequence)
10971		    (car tail))
10972		   ((memq org-todo-interpretation '(type priority))
10973		    (if (eq this-command last-command)
10974			(car tail)
10975		      (if (> (length tail) 0) org-done-string nil)))
10976		   (t nil)))
10977	   (next (if state (concat " " state " ") " "))
10978	   dostates)
10979      (replace-match next t t)
10980      (setq org-last-todo-state-is-todo
10981	    (not (equal state org-done-string)))
10982      (when org-log-done
10983	(setq dostates (and (eq org-todo-interpretation 'sequence)
10984			    (listp org-log-done) (memq 'state org-log-done)))
10985	(cond
10986	 ((and state (not this))
10987	  (org-add-planning-info nil nil 'closed)
10988	  (and dostates (org-add-log-maybe 'state state 'findpos)))
10989	 ((and state dostates)
10990	  (org-add-log-maybe 'state state 'findpos))
10991	 ((equal state org-done-string)
10992	  ;; Planning info calls the note-setting command.
10993	  (org-add-planning-info 'closed (org-current-time)
10994				 (if (org-get-repeat) nil 'scheduled))
10995	  (org-add-log-maybe 'done state 'findpos))))
10996      ;; Fixup tag positioning
10997      (and org-auto-align-tags (org-set-tags nil t))
10998      (run-hooks 'org-after-todo-state-change-hook)
10999      (and (equal state org-done-string) (org-auto-repeat-maybe))
11000      ))
11001  ;; Fixup cursor location if close to the keyword
11002  (if (and (outline-on-heading-p)
11003	   (not (bolp))
11004	   (save-excursion (beginning-of-line 1)
11005			   (looking-at org-todo-line-regexp))
11006	   (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11007      (progn
11008	(goto-char (or (match-end 2) (match-end 1)))
11009	(just-one-space))))
11010
11011(defun org-get-repeat ()
11012  "Return the REPEAT statement of this entry."
11013  (save-match-data
11014    (save-excursion
11015      (org-back-to-heading t)
11016      (if (re-search-forward
11017	   org-repeat-re (save-excursion (outline-next-heading) (point)) t)
11018	  (match-string 1)))))
11019
11020(defvar org-last-changed-timestamp)
11021(defvar org-log-post-message)
11022(defun org-auto-repeat-maybe ()
11023  "Check if the current headline contains a REPEAT key.
11024If yes, set TODO state back to what it was and change any SCHEDULED
11025or DEADLINE times the new date.
11026This function should be run in the `org-after-todo-state-change-hook'."
11027  ;; last-state is dynamically scoped into this function
11028  (let ((repeat (org-get-repeat))
11029	(whata '(("d" . day) ("m" . month) ("y" . year)))
11030	(msg "Entry repeats: ")
11031	(org-log-done)
11032	re type n what start)
11033    (when repeat
11034      (org-todo (if (eq 'org-todo-interpretation 'type)
11035		    last-state
11036		  (car org-todo-keywords)))
11037      (unless (memq 'org-add-log-note (default-value 'post-command-hook))
11038	;; Make sure a note is taken
11039	(let ((org-log-done '(done)))
11040	  (org-add-log-maybe 'done org-done-string 'findpos)))
11041      (org-back-to-heading t)
11042      (org-add-planning-info nil nil 'closed)
11043      (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11044		       org-deadline-time-regexp "\\)"))
11045      (while (re-search-forward
11046	      re (save-excursion (outline-next-heading) (point)) t)
11047	(setq type (if (match-end 1) org-scheduled-string org-deadline-string)
11048	      start 0)
11049	(while (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" repeat start)
11050	  (setq start (match-end 0)
11051		n (string-to-number (match-string 1 repeat))
11052		what (match-string 2 repeat))
11053	  (if (equal what "w") (setq n (* n 7) what "d"))
11054	  (org-timestamp-change n (cdr (assoc what whata))))
11055	(setq msg (concat msg type org-last-changed-timestamp " ")))
11056      (setq org-log-post-message msg)
11057      (message msg))))
11058
11059(defun org-show-todo-tree (arg)
11060  "Make a compact tree which shows all headlines marked with TODO.
11061The tree will show the lines where the regexp matches, and all higher
11062headlines above the match.
11063With \\[universal-argument] prefix, also show the DONE entries.
11064With a numeric prefix N, construct a sparse tree for the Nth element
11065of `org-todo-keywords'."
11066  (interactive "P")
11067  (let ((case-fold-search nil)
11068	(kwd-re
11069	 (cond ((null arg) org-not-done-regexp)
11070	       ((equal arg '(4)) org-todo-regexp)
11071	       ((<= (prefix-numeric-value arg) (length org-todo-keywords))
11072		(regexp-quote (nth (1- (prefix-numeric-value arg))
11073				   org-todo-keywords)))
11074	       (t (error "Invalid prefix argument: %s" arg)))))
11075    (message "%d TODO entries found"
11076	     (org-occur (concat "^" outline-regexp " +" kwd-re )))))
11077
11078(defun org-deadline ()
11079  "Insert the DEADLINE: string to make a deadline.
11080A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
11081to modify it to the correct date."
11082  (interactive)
11083  (org-add-planning-info 'deadline nil 'closed))
11084
11085(defun org-schedule ()
11086  "Insert the SCHEDULED: string to schedule a TODO item.
11087A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
11088to modify it to the correct date."
11089  (interactive)
11090  (org-add-planning-info 'scheduled nil 'closed))
11091
11092(defun org-add-planning-info (what &optional time &rest remove)
11093  "Insert new timestamp with keyword in the line directly after the headline.
11094WHAT indicates what kind of time stamp to add.  TIME indicated the time to use.
11095If non is given, the user is prompted for a date.
11096REMOVE indicates what kind of entries to remove.  An old WHAT entry will also
11097be removed."
11098  (interactive)
11099  (let (org-time-was-given)
11100    (when what (setq time (or time (org-read-date nil 'to-time))))
11101    (when (and org-insert-labeled-timestamps-at-point
11102	       (member what '(scheduled deadline)))
11103      (insert
11104       (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11105      (org-insert-time-stamp time org-time-was-given)
11106      (setq what nil))
11107    (save-excursion
11108      (save-restriction
11109	(let (col list elt ts buffer-invisibility-spec)
11110	  (org-back-to-heading t)
11111	  (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11112	  (goto-char (match-end 1))
11113	  (setq col (current-column))
11114	  (goto-char (1+ (match-end 0)))
11115	  (if (and (not (looking-at outline-regexp))
11116		   (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11117				       "[^\r\n]*"))
11118		   (not (equal (match-string 1) org-clock-string)))
11119	      (narrow-to-region (match-beginning 0) (match-end 0))
11120	    (insert "\n")
11121	    (backward-char 1)
11122	    (narrow-to-region (point) (point))
11123	    (indent-to-column col))
11124	  ;; Check if we have to remove something.
11125	  (setq list (cons what remove))
11126	  (while list
11127	    (setq elt (pop list))
11128	    (goto-char (point-min))
11129	    (when (or (and (eq elt 'scheduled)
11130			   (re-search-forward org-scheduled-time-regexp nil t))
11131		      (and (eq elt 'deadline)
11132			   (re-search-forward org-deadline-time-regexp nil t))
11133		      (and (eq elt 'closed)
11134			   (re-search-forward org-closed-time-regexp nil t)))
11135	      (replace-match "")
11136	      (if (looking-at "--+<[^>]+>") (replace-match ""))
11137	      (if (looking-at " +") (replace-match ""))))
11138	  (goto-char (point-max))
11139	  (when what
11140	    (insert
11141	     (if (not (equal (char-before) ?\ )) " " "")
11142	     (cond ((eq what 'scheduled) org-scheduled-string)
11143		   ((eq what 'deadline) org-deadline-string)
11144		   ((eq what 'closed) org-closed-string))
11145	     " ")
11146	    (org-insert-time-stamp time
11147				   (or org-time-was-given (eq what 'closed))
11148				   (eq what 'closed))
11149	    (end-of-line 1))
11150	  (goto-char (point-min))
11151	  (widen)
11152	  (if (looking-at "[ \t]+\r?\n")
11153	      (replace-match ""))
11154	  ts)))))
11155
11156(defvar org-log-note-marker (make-marker))
11157(defvar org-log-note-purpose nil)
11158(defvar org-log-note-state nil)
11159(defvar org-log-note-window-configuration nil)
11160(defvar org-log-note-return-to (make-marker))
11161(defvar org-log-post-message nil
11162  "Message to be displayed after a log note has been stored.
11163The auto-repeater uses this.")
11164
11165(defun org-add-log-maybe (&optional purpose state findpos)
11166  (save-excursion
11167    (when (and (listp org-log-done)
11168	       (memq purpose org-log-done))
11169      (when findpos
11170	(org-back-to-heading t)
11171	(looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11172			    "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11173			    "[^\r\n]*\\)?"))
11174	(goto-char (match-end 0)))
11175      (move-marker org-log-note-marker (point))
11176      (setq org-log-note-purpose purpose)
11177      (setq org-log-note-state state)
11178      (add-hook 'post-command-hook 'org-add-log-note 'append))))
11179
11180(defun org-add-log-note (&optional purpose)
11181  "Pop up a window for taking a note, and add this note later at point."
11182  (remove-hook 'post-command-hook 'org-add-log-note)
11183  (setq org-log-note-window-configuration (current-window-configuration))
11184  (delete-other-windows)
11185  (move-marker org-log-note-return-to (point))
11186  (switch-to-buffer (marker-buffer org-log-note-marker))
11187  (goto-char org-log-note-marker)
11188  (switch-to-buffer-other-window "*Org Note*")
11189  (erase-buffer)
11190  (let ((org-inhibit-startup t)) (org-mode))
11191  (insert (format "# Insert note for %s, finish with C-c C-c.\n\n"
11192		  (cond
11193		   ((eq org-log-note-purpose 'clock-out) "stopped clock")
11194		   ((eq org-log-note-purpose 'done)  "closed todo item")
11195		   ((eq org-log-note-purpose 'state) "state change")
11196		   (t (error "This should not happen")))))
11197  (org-set-local 'org-finish-function 'org-store-log-note))
11198
11199(defun org-store-log-note ()
11200  "Finish taking a log note, and insert it to where it belongs."
11201  (let ((txt (buffer-string))
11202	(note (cdr (assq org-log-note-purpose org-log-note-headings)))
11203	lines ind)
11204    (kill-buffer (current-buffer))
11205    (if (string-match "^#.*\n[ \t\n]*" txt)
11206	(setq txt (replace-match "" t t txt)))
11207    (if (string-match "\\s-+\\'" txt)
11208	(setq txt (replace-match "" t t txt)))
11209    (setq lines (org-split-string txt "\n"))
11210    (when (and note (string-match "\\S-" note))
11211      (setq note
11212	    (org-replace-escapes
11213	     note
11214	     (list (cons "%u" (user-login-name))
11215		   (cons "%U" user-full-name)
11216		   (cons "%t" (format-time-string
11217			       (org-time-stamp-format 'long 'inactive)
11218			       (current-time)))
11219		   (cons "%s" (if org-log-note-state
11220				  (concat "\"" org-log-note-state "\"")
11221				"")))))
11222      (if lines (setq note (concat note " \\\\")))
11223      (push note lines))
11224    (save-excursion
11225      (set-buffer (marker-buffer org-log-note-marker))
11226      (save-excursion
11227	(goto-char org-log-note-marker)
11228	(move-marker org-log-note-marker nil)
11229	(end-of-line 1)
11230	(if (not (bolp)) (insert "\n")) (indent-relative nil)
11231	(setq ind (concat (buffer-substring (point-at-bol) (point)) "    "))
11232	(insert "  - " (pop lines))
11233	(while lines
11234	  (insert "\n" ind (pop lines))))))
11235  (set-window-configuration org-log-note-window-configuration)
11236  (with-current-buffer (marker-buffer org-log-note-return-to)
11237    (goto-char org-log-note-return-to))
11238  (move-marker org-log-note-return-to nil)
11239  (and org-log-post-message (message org-log-post-message)))
11240
11241(defvar org-occur-highlights nil)
11242(make-variable-buffer-local 'org-occur-highlights)
11243
11244(defun org-occur (regexp &optional keep-previous callback)
11245  "Make a compact tree which shows all matches of REGEXP.
11246The tree will show the lines where the regexp matches, and all higher
11247headlines above the match.  It will also show the heading after the match,
11248to make sure editing the matching entry is easy.
11249If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11250call to `org-occur' will be kept, to allow stacking of calls to this
11251command.
11252If CALLBACK is non-nil, it is a function which is called to confirm
11253that the match should indeed be shown."
11254  (interactive "sRegexp: \nP")
11255  (or keep-previous (org-remove-occur-highlights nil nil t))
11256  (let ((cnt 0))
11257    (save-excursion
11258      (goto-char (point-min))
11259      (if (or (not keep-previous)          ; do not want to keep
11260	      (not org-occur-highlights))  ; no previous matches
11261	  ;; hide everything
11262	  (org-overview))
11263      (while (re-search-forward regexp nil t)
11264	(when (or (not callback)
11265		  (save-match-data (funcall callback)))
11266	  (setq cnt (1+ cnt))
11267	  (org-highlight-new-match (match-beginning 0) (match-end 0))
11268	  (org-show-context 'occur-tree))))
11269    (when org-remove-highlights-with-change
11270      (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11271		    nil 'local))
11272    (unless org-sparse-tree-open-archived-trees
11273      (org-hide-archived-subtrees (point-min) (point-max)))
11274    (run-hooks 'org-occur-hook)
11275    (if (interactive-p)
11276	(message "%d match(es) for regexp %s" cnt regexp))
11277    cnt))
11278
11279(defun org-show-context (&optional key)
11280  "Make sure point and context and visible.
11281How much context is shown depends upon the variables
11282`org-show-hierarchy-above', `org-show-following-heading'. and
11283`org-show-siblings'."
11284  (let ((heading-p   (org-on-heading-p t))
11285	(hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11286	(following-p (org-get-alist-option org-show-following-heading key))
11287	(siblings-p  (org-get-alist-option org-show-siblings key)))
11288    (catch 'exit
11289      ;; Show heading or entry text
11290      (if heading-p
11291	  (org-flag-heading nil)    ; only show the heading
11292	(and (or (org-invisible-p) (org-invisible-p2))
11293	     (org-show-hidden-entry)))    ; show entire entry
11294      (when following-p
11295	;; Show next sibling, or heading below text
11296	(save-excursion
11297	  (and (if heading-p (org-goto-sibling) (outline-next-heading))
11298	       (org-flag-heading nil))))
11299      (when siblings-p (org-show-siblings))
11300      (when hierarchy-p
11301	;; show all higher headings, possibly with siblings
11302	(save-excursion
11303	  (while (and (condition-case nil
11304			  (progn (org-up-heading-all 1) t)
11305			(error nil))
11306		      (not (bobp)))
11307	    (org-flag-heading nil)
11308	    (when siblings-p (org-show-siblings))))))))
11309
11310(defun org-reveal (&optional siblings)
11311  "Show current entry, hierarchy above it, and the following headline.
11312This can be used to show a consistent set of context around locations
11313exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11314not t for the search context.
11315
11316With optional argument SIBLINGS, on each level of the hierarchy all
11317siblings are shown.  This repairs the tree structure to what it would
11318look like when opened with hierarchical calls to `org-cycle'."
11319  (interactive "P")
11320  (let ((org-show-hierarchy-above t)
11321	(org-show-following-heading t)
11322	(org-show-siblings (if siblings t org-show-siblings)))
11323    (org-show-context nil)))
11324
11325(defun org-highlight-new-match (beg end)
11326  "Highlight from BEG to END and mark the highlight is an occur headline."
11327  (let ((ov (org-make-overlay beg end)))
11328    (org-overlay-put ov 'face 'secondary-selection)
11329    (push ov org-occur-highlights)))
11330
11331(defun org-remove-occur-highlights (&optional beg end noremove)
11332  "Remove the occur highlights from the buffer.
11333BEG and END are ignored.  If NOREMOVE is nil, remove this function
11334from the `before-change-functions' in the current buffer."
11335  (interactive)
11336  (unless org-inhibit-highlight-removal
11337    (mapc 'org-delete-overlay org-occur-highlights)
11338    (setq org-occur-highlights nil)
11339    (unless noremove
11340      (remove-hook 'before-change-functions
11341		   'org-remove-occur-highlights 'local))))
11342
11343;;;; Priorities
11344
11345(defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
11346  "Regular expression matching the priority indicator.")
11347
11348(defvar org-remove-priority-next-time nil)
11349
11350(defun org-priority-up ()
11351  "Increase the priority of the current item."
11352  (interactive)
11353  (org-priority 'up))
11354
11355(defun org-priority-down ()
11356  "Decrease the priority of the current item."
11357  (interactive)
11358  (org-priority 'down))
11359
11360(defun org-priority (&optional action)
11361  "Change the priority of an item by ARG.
11362ACTION can be set, up, or down."
11363  (interactive)
11364  (setq action (or action 'set))
11365  (let (current new news have remove)
11366    (save-excursion
11367      (org-back-to-heading)
11368      (if (looking-at org-priority-regexp)
11369	  (setq current (string-to-char (match-string 2))
11370		have t)
11371	(setq current org-default-priority))
11372      (cond
11373       ((eq action 'set)
11374	(message "Priority A-%c, SPC to remove: " org-lowest-priority)
11375	(setq new (read-char-exclusive))
11376	(cond ((equal new ?\ ) (setq remove t))
11377	      ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
11378	       (error "Priority must be between `%c' and `%c'"
11379		      ?A org-lowest-priority))))
11380       ((eq action 'up)
11381	(setq new (1- current)))
11382       ((eq action 'down)
11383	(setq new (1+ current)))
11384       (t (error "Invalid action")))
11385      (setq new (min (max ?A (upcase new)) org-lowest-priority))
11386      (setq news (format "%c" new))
11387      (if have
11388	  (if remove
11389	      (replace-match "" t t nil 1)
11390	    (replace-match news t t nil 2))
11391	(if remove
11392	    (error "No priority cookie found in line")
11393	  (looking-at org-todo-line-regexp)
11394	  (if (match-end 2)
11395	      (progn
11396		(goto-char (match-end 2))
11397		(insert " [#" news "]"))
11398	    (goto-char (match-beginning 3))
11399	    (insert "[#" news "] ")))))
11400    (if remove
11401	(message "Priority removed")
11402      (message "Priority of current item set to %s" news))))
11403
11404
11405(defun org-get-priority (s)
11406  "Find priority cookie and return priority."
11407  (save-match-data
11408    (if (not (string-match org-priority-regexp s))
11409	(* 1000 (- org-lowest-priority org-default-priority))
11410      (* 1000 (- org-lowest-priority
11411		 (string-to-char (match-string 2 s)))))))
11412
11413;;;; Tags
11414
11415(defun org-scan-tags (action matcher &optional todo-only)
11416  "Scan headline tags with inheritance and produce output ACTION.
11417ACTION can be `sparse-tree' or `agenda'.  MATCHER is a Lisp form to be
11418evaluated, testing if a given set of tags qualifies a headline for
11419inclusion.  When TODO-ONLY is non-nil, only lines with a TODO keyword
11420are included in the output."
11421  (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
11422		     (mapconcat 'regexp-quote
11423				(nreverse (cdr (reverse org-todo-keywords)))
11424				"\\|")
11425		     "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*$"))
11426	 (props (list 'face nil
11427		      'done-face 'org-done
11428		      'undone-face nil
11429		      'mouse-face 'highlight
11430		      'org-not-done-regexp org-not-done-regexp
11431		      'keymap org-agenda-keymap
11432		      'help-echo
11433		      (format "mouse-2 or RET jump to org file %s"
11434			      (abbreviate-file-name buffer-file-name))))
11435	 (case-fold-search nil)
11436         lspos
11437	 tags tags-list tags-alist (llast 0) rtn level category i txt
11438	 todo marker entry)
11439    (save-excursion
11440      (goto-char (point-min))
11441      (when (eq action 'sparse-tree) (org-overview))
11442      (while (re-search-forward re nil t)
11443	(catch :skip
11444	  (setq todo (if (match-end 1) (match-string 2))
11445		tags (if (match-end 4) (match-string 4)))
11446	  (goto-char (setq lspos (1+ (match-beginning 0))))
11447	  (setq level (funcall outline-level)
11448		category (org-get-category))
11449	  (setq i llast llast level)
11450	  ;; remove tag lists from same and sublevels
11451	  (while (>= i level)
11452	    (when (setq entry (assoc i tags-alist))
11453	      (setq tags-alist (delete entry tags-alist)))
11454	    (setq i (1- i)))
11455	  ;; add the nex tags
11456	  (when tags
11457	    (setq tags (mapcar 'downcase (org-split-string tags ":"))
11458		  tags-alist
11459		  (cons (cons level tags) tags-alist)))
11460	  ;; compile tags for current headline
11461	  (setq tags-list
11462		(if org-use-tag-inheritance
11463		    (apply 'append (mapcar 'cdr tags-alist))
11464		  tags))
11465	  (when (and (or (not todo-only) todo)
11466		     (eval matcher)
11467		     (or (not org-agenda-skip-archived-trees)
11468			 (not (member org-archive-tag tags-list))))
11469	    (and (eq action 'agenda) (org-agenda-skip))
11470	    ;; list this headline
11471	    (if (eq action 'sparse-tree)
11472		(progn
11473		  (org-show-context 'tags-tree))
11474	      (setq txt (org-format-agenda-item
11475			 ""
11476			 (concat
11477			  (if org-tags-match-list-sublevels
11478			      (make-string (1- level) ?.) "")
11479			  (org-get-heading))
11480			 category tags-list))
11481	      (goto-char lspos)
11482	      (setq marker (org-agenda-new-marker))
11483	      (org-add-props txt props
11484		'org-marker marker 'org-hd-marker marker 'org-category category)
11485	      (push txt rtn))
11486	    ;; if we are to skip sublevels, jump to end of subtree
11487	    (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
11488    (when (and (eq action 'sparse-tree)
11489	       (not org-sparse-tree-open-archived-trees))
11490      (org-hide-archived-subtrees (point-min) (point-max)))
11491    (nreverse rtn)))
11492
11493(defvar todo-only) ;; dynamically scoped
11494
11495(defun org-tags-sparse-tree (&optional todo-only match)
11496  "Create a sparse tree according to tags  string MATCH.
11497MATCH can contain positive and negative selection of tags, like
11498\"+WORK+URGENT-WITHBOSS\".
11499If optional argument TODO_ONLY is non-nil, only select lines that are
11500also TODO lines."
11501  (interactive "P")
11502  (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11503
11504(defun org-make-tags-matcher (match)
11505  "Create the TAGS//TODO matcher form for the selection string MATCH."
11506  ;; todo-only is scoped dynamically into this function, and the function
11507  ;; may change it it the matcher asksk for it.
11508  (unless match
11509    ;; Get a new match request, with completion
11510    (setq org-last-tags-completion-table
11511	  (or org-tag-alist
11512	      org-last-tags-completion-table))
11513    (setq match (completing-read
11514		 "Match: " 'org-tags-completion-function nil nil nil
11515		 'org-tags-history)))
11516
11517  ;; Parse the string and create a lisp form
11518  (let ((match0 match)
11519	(re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|[A-Za-z_@0-9]+\\)")
11520	minus tag mm
11521	tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11522	orterms term orlist re-p level-p)
11523    (if (string-match "/+" match)
11524	;; match contains also a todo-matching request
11525	(progn
11526	  (setq tagsmatch (substring match 0 (match-beginning 0))
11527		todomatch (substring match (match-end 0)))
11528	  (if (string-match "^!" todomatch)
11529	      (setq todo-only t todomatch (substring todomatch 1)))
11530	  (if (string-match "^\\s-*$" todomatch)
11531	      (setq todomatch nil)))
11532      ;; only matching tags
11533      (setq tagsmatch match todomatch nil))
11534
11535    ;; Make the tags matcher
11536    (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11537	(setq tagsmatcher t)
11538      (setq orterms (org-split-string tagsmatch "|") orlist nil)
11539      (while (setq term (pop orterms))
11540	(while (and (equal (substring term -1) "\\") orterms)
11541	  (setq term (concat term "|" (pop orterms)))) ; repair bad split
11542	(while (string-match re term)
11543	  (setq minus (and (match-end 1)
11544			   (equal (match-string 1 term) "-"))
11545		tag (match-string 2 term)
11546		re-p (equal (string-to-char tag) ?{)
11547		level-p (match-end 3)
11548		mm (cond
11549		    (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11550		    (level-p `(= level ,(string-to-number
11551					 (match-string 3 term))))
11552		    (t `(member ,(downcase tag) tags-list)))
11553		mm (if minus (list 'not mm) mm)
11554		term (substring term (match-end 0)))
11555	  (push mm tagsmatcher))
11556	(push (if (> (length tagsmatcher) 1)
11557		  (cons 'and tagsmatcher)
11558		(car tagsmatcher))
11559	      orlist)
11560	(setq tagsmatcher nil))
11561      (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist))))
11562
11563    ;; Make the todo matcher
11564    (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11565	(setq todomatcher t)
11566      (setq orterms (org-split-string todomatch "|") orlist nil)
11567      (while (setq term (pop orterms))
11568	(while (string-match re term)
11569	  (setq minus (and (match-end 1)
11570			   (equal (match-string 1 term) "-"))
11571		kwd (match-string 2 term)
11572		re-p (equal (string-to-char kwd) ?{)
11573		term (substring term (match-end 0))
11574		mm (if re-p
11575		       `(string-match  ,(substring kwd 1 -1) todo)
11576		     (list 'equal 'todo kwd))
11577		mm (if minus (list 'not mm) mm))
11578	  (push mm todomatcher))
11579	(push (if (> (length todomatcher) 1)
11580		  (cons 'and todomatcher)
11581		(car todomatcher))
11582	      orlist)
11583	(setq todomatcher nil))
11584      (setq todomatcher (if (> (length orlist) 1)
11585			    (cons 'or orlist) (car orlist))))
11586
11587    ;; Return the string and lisp forms of the matcher
11588    (setq matcher (if todomatcher
11589		      (list 'and tagsmatcher todomatcher)
11590		    tagsmatcher))
11591    (cons match0 matcher)))
11592
11593(defun org-match-any-p (re list)
11594  "Does re match any element of list?"
11595  (setq list (mapcar (lambda (x) (string-match re x)) list))
11596  (delq nil list))
11597
11598(defvar org-add-colon-after-tag-completion nil)  ;; dynamically skoped param
11599(defvar org-tags-overlay (org-make-overlay 1 1))
11600(org-detach-overlay org-tags-overlay)
11601
11602(defun org-set-tags (&optional arg just-align)
11603  "Set the tags for the current headline.
11604With prefix ARG, realign all tags in headings in the current buffer."
11605  (interactive "P")
11606  (let* ((re (concat "^" outline-regexp))
11607	 (current (org-get-tags))
11608	 table current-tags inherited-tags ; computed below when needed
11609	 tags p0 c0 c1 rpl)
11610    (if arg
11611	(save-excursion
11612	  (goto-char (point-min))
11613	  (let (buffer-invisibility-spec)  ; Emacs 21 compatibility
11614	    (while (re-search-forward re nil t)
11615	      (org-set-tags nil t)
11616	      (end-of-line 1)))
11617	  (message "All tags realigned to column %d" org-tags-column))
11618      (if just-align
11619	  (setq tags current)
11620	;; Get a new set of tags from the user
11621	(save-excursion
11622	  (setq table (or org-tag-alist (org-get-buffer-tags))
11623		org-last-tags-completion-table table
11624		current-tags (org-split-string current ":")
11625		inherited-tags (nreverse
11626				(nthcdr (length current-tags)
11627					(nreverse (org-get-tags-at))))
11628		tags
11629		(if (or (eq t org-use-fast-tag-selection)
11630			(and org-use-fast-tag-selection
11631			     (delq nil (mapcar 'cdr table))))
11632		    (org-fast-tag-selection current-tags inherited-tags table)
11633		  (let ((org-add-colon-after-tag-completion t))
11634		    (org-trim
11635		     (completing-read "Tags: " 'org-tags-completion-function
11636				      nil nil current 'org-tags-history))))))
11637	(while (string-match "[-+&]+" tags)
11638	  ;; No boolean logic, just a list
11639	  (setq tags (replace-match ":" t t tags))))
11640      (if (string-match "\\`[\t ]*\\'" tags)
11641          (setq tags "")
11642	(unless (string-match ":$" tags) (setq tags (concat tags ":")))
11643	(unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11644
11645      ;; Insert new tags at the correct column
11646      (beginning-of-line 1)
11647      (if (re-search-forward
11648	   (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11649	   (point-at-eol) t)
11650	  (progn
11651	    (if (equal tags "")
11652		(setq rpl "")
11653	      (goto-char (match-beginning 0))
11654	      (setq c0 (current-column) p0 (point)
11655		    c1 (max (1+ c0) (if (> org-tags-column 0)
11656					org-tags-column
11657				      (- (- org-tags-column) (length tags))))
11658		    rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11659	    (replace-match rpl t t)
11660	    (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
11661	    tags)
11662	(error "Tags alignment failed")))))
11663
11664(defun org-tags-completion-function (string predicate &optional flag)
11665  (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11666	   (confirm (lambda (x) (stringp (car x)))))
11667    (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11668        (setq s1 (match-string 1 string)
11669              s2 (match-string 2 string))
11670      (setq s1 "" s2 string))
11671    (cond
11672     ((eq flag nil)
11673      ;; try completion
11674      (setq rtn (try-completion s2 ctable confirm))
11675      (if (stringp rtn)
11676	  (concat s1 s2 (substring rtn (length s2))
11677		  (if (and org-add-colon-after-tag-completion
11678			   (assoc rtn ctable))
11679		      ":" "")))
11680      )
11681     ((eq flag t)
11682      ;; all-completions
11683      (all-completions s2 ctable confirm)
11684      )
11685     ((eq flag 'lambda)
11686      ;; exact match?
11687      (assoc s2 ctable)))
11688    ))
11689
11690(defun org-fast-tag-insert (kwd tags face &optional end)
11691  "Insert KDW, and the TAGS, the latter with face FACE.  Also inser END."
11692  (insert (format "%-12s" (concat kwd ":"))
11693	  (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11694	  (or end "")))
11695
11696(defun org-fast-tag-show-exit (flag)
11697  (save-excursion
11698    (goto-line 3)
11699    (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11700	(replace-match ""))
11701    (when flag
11702      (end-of-line 1)
11703      (move-to-column (- (window-width) 19) t)
11704      (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11705
11706(defun org-set-current-tags-overlay (current prefix)
11707  (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11708    (if (featurep 'xemacs)
11709	(org-overlay-display org-tags-overlay (concat prefix s)
11710			     'secondary-selection)
11711      (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11712      (org-overlay-display org-tags-overlay (concat prefix s)))))
11713
11714(defun org-fast-tag-selection (current inherited table)
11715  "Fast tag selection with single keys.
11716CURRENT is the current list of tags in the headline, INHERITED is the
11717list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11718possibly with grouping information.
11719If the keys are nil, a-z are automatically assigned.
11720Returns the new tags string, or nil to not change the current settings."
11721  (let* ((maxlen (apply 'max (mapcar
11722			      (lambda (x)
11723				(if (stringp (car x)) (string-width (car x)) 0))
11724			      table)))
11725	 (buf (current-buffer))
11726	 (expert (eq org-fast-tag-selection-single-key 'expert))
11727	 (buffer-tags nil)
11728	 (fwidth (+ maxlen 3 1 3))
11729	 (ncol (/ (- (window-width) 4) fwidth))
11730	 (i-face 'org-done)
11731	 (c-face 'org-tag)
11732	 tg cnt e c char c1 c2 ntable tbl rtn
11733	 ov-start ov-end ov-prefix
11734	 (exit-after-next org-fast-tag-selection-single-key)
11735	 groups ingroup)
11736    (save-excursion
11737      (beginning-of-line 1)
11738      (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
11739	  (setq ov-start (match-beginning 1)
11740		ov-end (match-end 1)
11741		ov-prefix "")
11742	(setq ov-start (1- (point-at-eol))
11743	      ov-end (1+ ov-start))
11744	(skip-chars-forward "^\n\r")
11745	(setq ov-prefix
11746	      (concat
11747	       (buffer-substring (1- (point)) (point))
11748	       (if (> (current-column) org-tags-column)
11749		   " "
11750		 (make-string (- org-tags-column (current-column)) ?\ ))))))
11751    (org-move-overlay org-tags-overlay ov-start ov-end)
11752    (save-window-excursion
11753      (if expert
11754	  (set-buffer (get-buffer-create " *Org tags*"))
11755	(delete-other-windows)
11756	(split-window-vertically)
11757	(switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11758      (erase-buffer)
11759      (org-fast-tag-insert "Inherited" inherited i-face "\n")
11760      (org-fast-tag-insert "Current" current c-face "\n\n")
11761      (org-fast-tag-show-exit exit-after-next)
11762      (org-set-current-tags-overlay current ov-prefix)
11763      (setq tbl table char ?a cnt 0)
11764      (while (setq e (pop tbl))
11765	(cond
11766	 ((equal e '(:startgroup))
11767	  (push '() groups) (setq ingroup t)
11768	  (when (not (= cnt 0))
11769	    (setq cnt 0)
11770	    (insert "\n"))
11771	  (insert "{ "))
11772	 ((equal e '(:endgroup))
11773	  (setq ingroup nil cnt 0)
11774	  (insert "}\n"))
11775	 (t
11776	  (setq tg (car e) c2 nil)
11777	  (if (cdr e)
11778	      (setq c (cdr e))
11779	    ;; automatically assign a character.
11780	    (setq c1 (string-to-char
11781		      (downcase (substring
11782				 tg (if (= (string-to-char tg) ?@) 1 0)))))
11783	    (if (or (rassoc c1 ntable) (rassoc c1 table))
11784		(while (or (rassoc char ntable) (rassoc char table))
11785		  (setq char (1+ char)))
11786	      (setq c2 c1))
11787	    (setq c (or c2 char)))
11788	  (if ingroup (push tg (car groups)))
11789	  (setq tg (org-add-props tg nil 'face
11790				  (cond
11791				   ((member tg current) c-face)
11792				   ((member tg inherited) i-face)
11793				   (t nil))))
11794	  (if (and (= cnt 0) (not ingroup)) (insert "  "))
11795	  (insert "[" c "] " tg (make-string
11796				 (- fwidth 4 (length tg)) ?\ ))
11797	  (push (cons tg c) ntable)
11798	  (when (= (setq cnt (1+ cnt)) ncol)
11799	    (insert "\n")
11800	    (if ingroup (insert "  "))
11801	    (setq cnt 0)))))
11802      (setq ntable (nreverse ntable))
11803      (insert "\n")
11804      (goto-char (point-min))
11805      (if (and (not expert) (fboundp 'fit-window-to-buffer))
11806	  (fit-window-to-buffer))
11807      (setq rtn
11808	    (catch 'exit
11809	      (while t
11810		(message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11811			 (if groups " [!] no groups" " [!]groups")
11812			 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11813		(setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11814		(cond
11815		 ((= c ?\r) (throw 'exit t))
11816		 ((= c ?!)
11817		  (setq groups (not groups))
11818		  (goto-char (point-min))
11819		  (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11820		 ((= c ?\C-c)
11821		  (if (not expert)
11822		      (org-fast-tag-show-exit
11823		       (setq exit-after-next (not exit-after-next)))
11824		    (setq expert nil)
11825		    (delete-other-windows)
11826		    (split-window-vertically)
11827		    (switch-to-buffer-other-window " *Org tags*")
11828		    (and (fboundp 'fit-window-to-buffer)
11829			 (fit-window-to-buffer))))
11830		 ((or (= c ?\C-g)
11831		      (and (= c ?q) (not (rassoc c ntable))))
11832		  (org-detach-overlay org-tags-overlay)
11833		  (setq quit-flag t))
11834		 ((= c ?\ )
11835		  (setq current nil)
11836		  (if exit-after-next (setq exit-after-next 'now)))
11837		 ((= c ?\t)
11838		  (condition-case nil
11839		      (setq tg (completing-read
11840				"Tag: "
11841				(or buffer-tags
11842				    (with-current-buffer buf
11843				      (org-get-buffer-tags)))))
11844		    (quit (setq tg "")))
11845		  (when (string-match "\\S-" tg)
11846		    (add-to-list 'buffer-tags (list tg))
11847		    (if (member tg current)
11848			(setq current (delete tg current))
11849		      (push tg current)))
11850		  (if exit-after-next (setq exit-after-next 'now)))
11851		 ((setq e (rassoc c ntable) tg (car e))
11852		  (if (member tg current)
11853		      (setq current (delete tg current))
11854		    (loop for g in groups do
11855			  (if (member tg g)
11856			      (mapcar (lambda (x)
11857					(setq current (delete x current)))
11858				      g)))
11859		    (push tg current))
11860		  (if exit-after-next (setq exit-after-next 'now))))
11861
11862		;; Create a sorted list
11863		(setq current
11864		      (sort current
11865			    (lambda (a b)
11866			      (assoc b (cdr (memq (assoc a ntable) ntable))))))
11867		(if (eq exit-after-next 'now) (throw 'exit t))
11868		(goto-char (point-min))
11869		(beginning-of-line 2)
11870		(delete-region (point) (point-at-eol))
11871		(org-fast-tag-insert "Current" current c-face)
11872		(org-set-current-tags-overlay current ov-prefix)
11873		(while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
11874		  (setq tg (match-string 1))
11875		  (add-text-properties (match-beginning 1) (match-end 1)
11876				       (list 'face
11877					     (cond
11878					      ((member tg current) c-face)
11879					      ((member tg inherited) i-face)
11880					      (t nil)))))
11881		(goto-char (point-min)))))
11882      (org-detach-overlay org-tags-overlay)
11883      (if rtn
11884	  (mapconcat 'identity current ":")
11885	nil))))
11886
11887(defun org-get-tags ()
11888  "Get the TAGS string in the current headline."
11889  (unless (org-on-heading-p t)
11890    (error "Not on a heading"))
11891  (save-excursion
11892    (beginning-of-line 1)
11893    (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
11894	(org-match-string-no-properties 1)
11895      "")))
11896
11897(defun org-get-buffer-tags ()
11898  "Get a table of all tags used in the buffer, for completion."
11899  (let (tags)
11900    (save-excursion
11901      (goto-char (point-min))
11902      (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
11903	(mapc (lambda (x) (add-to-list 'tags x))
11904	      (org-split-string (org-match-string-no-properties 1) ":"))))
11905    (mapcar 'list tags)))
11906
11907;;;; Timestamps
11908
11909(defvar org-last-changed-timestamp nil)
11910(defvar org-time-was-given) ; dynamically scoped parameter
11911(defvar org-ts-what) ; dynamically scoped parameter
11912
11913(defun org-time-stamp (arg)
11914  "Prompt for a date/time and insert a time stamp.
11915If the user specifies a time like HH:MM, or if this command is called
11916with a prefix argument, the time stamp will contain date and time.
11917Otherwise, only the date will be included.  All parts of a date not
11918specified by the user will be filled in from the current date/time.
11919So if you press just return without typing anything, the time stamp
11920will represent the current date/time.  If there is already a timestamp
11921at the cursor, it will be modified."
11922  (interactive "P")
11923  (let (org-time-was-given time)
11924    (cond
11925     ((and (org-at-timestamp-p)
11926	   (eq last-command 'org-time-stamp)
11927	   (eq this-command 'org-time-stamp))
11928      (insert "--")
11929      (setq time (let ((this-command this-command))
11930		  (org-read-date arg 'totime)))
11931      (org-insert-time-stamp time (or org-time-was-given arg)))
11932     ((org-at-timestamp-p)
11933      (setq time (let ((this-command this-command))
11934		   (org-read-date arg 'totime)))
11935      (when (org-at-timestamp-p) ; just to get the match data
11936	(replace-match "")
11937	(setq org-last-changed-timestamp
11938	      (org-insert-time-stamp time (or org-time-was-given arg))))
11939      (message "Timestamp updated"))
11940     (t
11941      (setq time (let ((this-command this-command))
11942		   (org-read-date arg 'totime)))
11943      (org-insert-time-stamp time (or org-time-was-given arg))))))
11944
11945(defun org-time-stamp-inactive (&optional arg)
11946  "Insert an inactive time stamp.
11947An inactive time stamp is enclosed in square brackets instead of angle
11948brackets.  It is inactive in the sense that it does not trigger agenda entries,
11949does not link to the calendar and cannot be changed with the S-cursor keys.
11950So these are more for recording a certain time/date."
11951  (interactive "P")
11952  (let (org-time-was-given time)
11953    (setq time (org-read-date arg 'totime))
11954    (org-insert-time-stamp time (or org-time-was-given arg) 'inactive)))
11955
11956(defvar org-date-ovl (org-make-overlay 1 1))
11957(org-overlay-put org-date-ovl 'face 'org-warning)
11958(org-detach-overlay org-date-ovl)
11959
11960(defvar org-ans1) ; dynamically scoped parameter
11961(defvar org-ans2) ; dynamically scoped parameter
11962
11963(defun org-read-date (&optional with-time to-time from-string prompt)
11964  "Read a date and make things smooth for the user.
11965The prompt will suggest to enter an ISO date, but you can also enter anything
11966which will at least partially be understood by `parse-time-string'.
11967Unrecognized parts of the date will default to the current day, month, year,
11968hour and minute.  For example,
11969  3-2-5         --> 2003-02-05
11970  feb 15        --> currentyear-02-15
11971  sep 12 9      --> 2009-09-12
11972  12:45         --> today 12:45
11973  22 sept 0:34  --> currentyear-09-22 0:34
11974  12            --> currentyear-currentmonth-12
11975  Fri           --> nearest Friday (today or later)
11976  +4            --> four days from today (only if +N is the only thing given)
11977  etc.
11978The function understands only English month and weekday abbreviations,
11979but this can be configured with the variables `parse-time-months' and
11980`parse-time-weekdays'.
11981
11982While prompting, a calendar is popped up - you can also select the
11983date with the mouse (button 1).  The calendar shows a period of three
11984months.  To scroll it to other months, use the keys `>' and `<'.
11985If you don't like the calendar, turn it off with
11986       \(setq org-popup-calendar-for-date-prompt nil)
11987
11988With optional argument TO-TIME, the date will immediately be converted
11989to an internal time.
11990With an optional argument WITH-TIME, the prompt will suggest to also
11991insert a time.  Note that when WITH-TIME is not set, you can still
11992enter a time, and this function will inform the calling routine about
11993this change.  The calling routine may then choose to change the format
11994used to insert the time stamp into the buffer to include the time."
11995  (require 'parse-time)
11996  (let* ((org-time-stamp-rounding-minutes
11997	  (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
11998	 (ct (org-current-time))
11999	 (default-time
12000	   ;; Default time is either today, or, when entering a range,
12001	   ;; the range start.
12002	   (if (save-excursion
12003		 (re-search-backward
12004		  (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12005		  (- (point) 20) t))
12006	       (apply
12007		'encode-time
12008		(mapcar (lambda(x) (or x 0))
12009			(parse-time-string (match-string 1))))
12010	     ct))
12011	 (calendar-move-hook nil)
12012	 (view-diary-entries-initially nil)
12013	 (view-calendar-holidays-initially nil)
12014	 (timestr (format-time-string
12015		   (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
12016	 (prompt (concat (if prompt (concat prompt " ") "")
12017			 (format "YYYY-MM-DD [%s]: " timestr)))
12018	 ans (org-ans0 "") org-ans1 org-ans2 (deltadays 0)
12019	 second minute hour day month year tl wday wday1)
12020
12021    (cond
12022     (from-string (setq ans from-string))
12023     (org-popup-calendar-for-date-prompt
12024      (save-excursion
12025	(save-window-excursion
12026	  (calendar)
12027	  (calendar-forward-day (- (time-to-days default-time)
12028				   (calendar-absolute-from-gregorian
12029				    (calendar-current-date))))
12030	  (org-eval-in-calendar nil)
12031	  (let* ((old-map (current-local-map))
12032		 (map (copy-keymap calendar-mode-map))
12033		 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12034	    (define-key map (kbd "RET") 'org-calendar-select)
12035	    (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
12036	      'org-calendar-select-mouse)
12037	    (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
12038	      'org-calendar-select-mouse)
12039	    (define-key minibuffer-local-map [(meta shift left)]
12040	      (lambda () (interactive)
12041		(org-eval-in-calendar '(calendar-backward-month 1))))
12042	    (define-key minibuffer-local-map [(meta shift right)]
12043	      (lambda () (interactive)
12044		(org-eval-in-calendar '(calendar-forward-month 1))))
12045	    (define-key minibuffer-local-map [(shift up)]
12046	      (lambda () (interactive)
12047		(org-eval-in-calendar '(calendar-backward-week 1))))
12048	    (define-key minibuffer-local-map [(shift down)]
12049	      (lambda () (interactive)
12050		(org-eval-in-calendar '(calendar-forward-week 1))))
12051	    (define-key minibuffer-local-map [(shift left)]
12052	      (lambda () (interactive)
12053		(org-eval-in-calendar '(calendar-backward-day 1))))
12054	    (define-key minibuffer-local-map [(shift right)]
12055	      (lambda () (interactive)
12056		(org-eval-in-calendar '(calendar-forward-day 1))))
12057	    (define-key minibuffer-local-map ">"
12058	      (lambda () (interactive)
12059		(org-eval-in-calendar '(scroll-calendar-left 1))))
12060	    (define-key minibuffer-local-map "<"
12061	      (lambda () (interactive)
12062		(org-eval-in-calendar '(scroll-calendar-right 1))))
12063	    (unwind-protect
12064		(progn
12065		  (use-local-map map)
12066		  (setq org-ans0 (read-string prompt "" nil nil))
12067;		  (if (not (string-match "\\S-" org-ans0)) (setq org-ans0 nil))
12068		  ;; org-ans0: from prompt
12069		  ;; org-ans1: from mouse click
12070		  ;; org-ans2: from calendar motion
12071		  (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12072	      (use-local-map old-map))))))
12073     (t ; Naked prompt only
12074      (setq ans (read-string prompt "" nil timestr))))
12075    (org-detach-overlay org-date-ovl)
12076
12077    (if (string-match "^[ \t]*[-+][0-9]+[ \t]*$" org-ans0)
12078	(setq deltadays (string-to-number ans) ans ""))
12079
12080    (if (string-match
12081	 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12082	(progn
12083	  (setq year (if (match-end 2)
12084			 (string-to-number (match-string 2 ans))
12085		       (string-to-number (format-time-string "%Y")))
12086		month (string-to-number (match-string 3 ans))
12087		day (string-to-number (match-string 4 ans)))
12088	  (if (< year 100) (setq year (+ 2000 year)))
12089	  (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12090				   t nil ans))))
12091    (setq tl (parse-time-string ans)
12092	  year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
12093	  month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
12094	  day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
12095	  hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
12096	  minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
12097	  second (or (nth 0 tl) 0)
12098	  wday (nth 6 tl))
12099    (setq day (+ day deltadays))
12100    (when (and wday (not (nth 3 tl)))
12101      ;; Weekday was given, but no day, so pick that day in the week
12102      ;; on or after the derived date.
12103      (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12104      (unless (equal wday wday1)
12105	(setq day (+ day (% (- wday wday1 -7) 7)))))
12106    (if (and (boundp 'org-time-was-given)
12107	     (nth 2 tl))
12108	(setq org-time-was-given t))
12109    (if (< year 100) (setq year (+ 2000 year)))
12110    (if to-time
12111	(encode-time second minute hour day month year)
12112      (if (or (nth 1 tl) (nth 2 tl))
12113	  (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
12114	(format "%04d-%02d-%02d" year month day)))))
12115
12116(defun org-eval-in-calendar (form)
12117  "Eval FORM in the calendar window and return to current window.
12118Also, store the cursor date in variable org-ans2."
12119  (let ((sw (selected-window)))
12120    (select-window (get-buffer-window "*Calendar*"))
12121    (eval form)
12122    (when (calendar-cursor-to-date)
12123      (let* ((date (calendar-cursor-to-date))
12124	     (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12125	(setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12126    (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12127    (select-window sw)))
12128
12129(defun org-calendar-select ()
12130  "Return to `org-read-date' with the date currently selected.
12131This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12132  (interactive)
12133  (when (calendar-cursor-to-date)
12134    (let* ((date (calendar-cursor-to-date))
12135	   (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12136      (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12137    (if (active-minibuffer-window) (exit-minibuffer))))
12138
12139(defun org-insert-time-stamp (time &optional with-hm inactive pre post)
12140  "Insert a date stamp for the date given by the internal TIME.
12141WITH-HM means, use the stamp format that includes the time of the day.
12142INACTIVE means use square brackets instead of angular ones, so that the
12143stamp will not contribute to the agenda.
12144PRE and POST are optional strings to be inserted before and after the
12145stamp.
12146The command returns the inserted time stamp."
12147  (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12148	stamp)
12149    (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12150    (insert (or pre ""))
12151    (insert (setq stamp (format-time-string fmt time)))
12152    (insert (or post ""))
12153    stamp))
12154
12155(defun org-toggle-time-stamp-overlays ()
12156  "Toggle the use of custom time stamp formats."
12157  (interactive)
12158  (setq org-display-custom-times (not org-display-custom-times))
12159  (unless org-display-custom-times
12160    (let ((p (point-min)) (bmp (buffer-modified-p)))
12161      (while (setq p (next-single-property-change p 'display))
12162	(if (and (get-text-property p 'display)
12163		 (eq (get-text-property p 'face) 'org-date))
12164	    (remove-text-properties
12165	     p (setq p (next-single-property-change p 'display))
12166	     '(display t))))
12167      (set-buffer-modified-p bmp)))
12168  (if (featurep 'xemacs)
12169      (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12170  (org-restart-font-lock)
12171  (setq org-table-may-need-update t)
12172  (if org-display-custom-times
12173      (message "Time stamps are overlayed with custom format")
12174    (message "Time stamp overlays removed")))
12175
12176(defun org-display-custom-time (beg end)
12177  "Overlay modified time stamp format over timestamp between BED and END."
12178  (let* ((t1 (save-match-data
12179	       (org-parse-time-string (buffer-substring beg end) t)))
12180	 (w1 (- end beg))
12181	 (with-hm (and (nth 1 t1) (nth 2 t1)))
12182	 (tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats))
12183	 (time (org-fix-decoded-time t1))
12184	 (str (org-add-props
12185		  (format-time-string
12186		   (substring tf 1 -1) (apply 'encode-time time))
12187		  nil 'mouse-face 'highlight))
12188	 (w2 (length str)))
12189    (if (not (= w2 w1))
12190	(add-text-properties (1+ beg) (+ 2 beg)
12191			     (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12192    (if (featurep 'xemacs)
12193	(progn
12194	  (put-text-property beg end 'invisible t)
12195	  (put-text-property beg end 'end-glyph (make-glyph str)))
12196      (put-text-property beg end 'display str))))
12197
12198(defun org-translate-time (string)
12199  "Translate all timestamps in STRING to custom format.
12200But do this only if the variable `org-display-custom-times' is set."
12201  (when org-display-custom-times
12202    (save-match-data
12203      (let* ((start 0)
12204	     (re org-ts-regexp-both)
12205	     t1 with-hm inactive tf time str beg end)
12206	(while (setq start (string-match re string start))
12207	  (setq beg (match-beginning 0)
12208		end (match-end 0)
12209		t1 (save-match-data
12210		     (org-parse-time-string (substring string beg end) t))
12211		with-hm (and (nth 1 t1) (nth 2 t1))
12212		inactive (equal (substring string beg (1+ beg)) "[")
12213		tf (funcall (if with-hm 'cdr 'car)
12214			    org-time-stamp-custom-formats)
12215		time (org-fix-decoded-time t1)
12216		str (format-time-string
12217		     (concat
12218		      (if inactive "[" "<") (substring tf 1 -1)
12219		      (if inactive "]" ">"))
12220		     (apply 'encode-time time))
12221		string (replace-match str t t string)
12222		start (+ start (length str)))))))
12223  string)
12224
12225(defun org-fix-decoded-time (time)
12226  "Set 0 instead of nil for the first 6 elements of time.
12227Don't touch the rest."
12228  (let ((n 0))
12229    (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12230
12231(defun org-days-to-time (timestamp-string)
12232  "Difference between TIMESTAMP-STRING and now in days."
12233  (- (time-to-days (org-time-string-to-time timestamp-string))
12234     (time-to-days (current-time))))
12235
12236(defun org-deadline-close (timestamp-string &optional ndays)
12237  "Is the time in TIMESTAMP-STRING close to the current date?"
12238  (and (< (org-days-to-time timestamp-string)
12239	  (or ndays org-deadline-warning-days))
12240       (not (org-entry-is-done-p))))
12241
12242(defun org-calendar-select-mouse (ev)
12243  "Return to `org-read-date' with the date currently selected.
12244This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12245  (interactive "e")
12246  (mouse-set-point ev)
12247  (when (calendar-cursor-to-date)
12248    (let* ((date (calendar-cursor-to-date))
12249	   (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12250      (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12251    (if (active-minibuffer-window) (exit-minibuffer))))
12252
12253(defun org-check-deadlines (ndays)
12254  "Check if there are any deadlines due or past due.
12255A deadline is considered due if it happens within `org-deadline-warning-days'
12256days from today's date.  If the deadline appears in an entry marked DONE,
12257it is not shown.  The prefix arg NDAYS can be used to test that many
12258days.  If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12259  (interactive "P")
12260  (let* ((org-warn-days
12261	  (cond
12262	   ((equal ndays '(4)) 100000)
12263	   (ndays (prefix-numeric-value ndays))
12264	   (t org-deadline-warning-days)))
12265	 (case-fold-search nil)
12266	 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12267	 (callback
12268	  (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12269
12270    (message "%d deadlines past-due or due within %d days"
12271	     (org-occur regexp nil callback)
12272	     org-warn-days)))
12273
12274(defun org-evaluate-time-range (&optional to-buffer)
12275  "Evaluate a time range by computing the difference between start and end.
12276Normally the result is just printed in the echo area, but with prefix arg
12277TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12278If the time range is actually in a table, the result is inserted into the
12279next column.
12280For time difference computation, a year is assumed to be exactly 365
12281days in order to avoid rounding problems."
12282  (interactive "P")
12283  (or
12284   (org-clock-update-time-maybe)
12285   (save-excursion
12286     (unless (org-at-date-range-p)
12287       (goto-char (point-at-bol))
12288       (re-search-forward org-tr-regexp (point-at-eol) t))
12289     (if (not (org-at-date-range-p))
12290	 (error "Not at a time-stamp range, and none found in current line")))
12291   (let* ((ts1 (match-string 1))
12292	  (ts2 (match-string 2))
12293	  (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12294	  (match-end (match-end 0))
12295	  (time1 (org-time-string-to-time ts1))
12296	  (time2 (org-time-string-to-time ts2))
12297	  (t1 (time-to-seconds time1))
12298	  (t2 (time-to-seconds time2))
12299	  (diff (abs (- t2 t1)))
12300	  (negative (< (- t2 t1) 0))
12301	  ;; (ys (floor (* 365 24 60 60)))
12302	  (ds (* 24 60 60))
12303	  (hs (* 60 60))
12304	  (fy "%dy %dd %02d:%02d")
12305	  (fy1 "%dy %dd")
12306	  (fd "%dd %02d:%02d")
12307	  (fd1 "%dd")
12308	  (fh "%02d:%02d")
12309	  y d h m align)
12310     (if havetime
12311	 (setq ; y (floor (/ diff ys))  diff (mod diff ys)
12312	  y 0
12313	  d (floor (/ diff ds))  diff (mod diff ds)
12314	  h (floor (/ diff hs))  diff (mod diff hs)
12315	  m (floor (/ diff 60)))
12316       (setq ; y (floor (/ diff ys))  diff (mod diff ys)
12317	y 0
12318	d (floor (+ (/ diff ds) 0.5))
12319	h 0 m 0))
12320     (if (not to-buffer)
12321	 (message (org-make-tdiff-string y d h m))
12322       (when (org-at-table-p)
12323	 (goto-char match-end)
12324	 (setq align t)
12325	 (and (looking-at " *|") (goto-char (match-end 0))))
12326       (if (looking-at
12327	    "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12328	   (replace-match ""))
12329       (if negative (insert " -"))
12330       (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12331	 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12332	   (insert " " (format fh h m))))
12333       (if align (org-table-align))
12334       (message "Time difference inserted")))))
12335
12336(defun org-make-tdiff-string (y d h m)
12337  (let ((fmt "")
12338	(l nil))
12339    (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12340		      l (push y l)))
12341    (if (> d 0) (setq fmt (concat fmt "%d day"  (if (> d 1) "s" "") " ")
12342		      l (push d l)))
12343    (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12344		      l (push h l)))
12345    (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12346		      l (push m l)))
12347    (apply 'format fmt (nreverse l))))
12348
12349(defun org-time-string-to-time (s)
12350  (apply 'encode-time (org-parse-time-string s)))
12351
12352(defun org-parse-time-string (s &optional nodefault)
12353  "Parse the standard Org-mode time string.
12354This should be a lot faster than the normal `parse-time-string'.
12355If time is not given, defaults to 0:00.  However, with optional NODEFAULT,
12356hour and minute fields will be nil if not given."
12357  (if (string-match org-ts-regexp1 s)
12358      (list 0
12359	    (if (or (match-beginning 8) (not nodefault))
12360		(string-to-number (or (match-string 8 s) "0")))
12361	    (if (or (match-beginning 7) (not nodefault))
12362		(string-to-number (or (match-string 7 s) "0")))
12363	    (string-to-number (match-string 4 s))
12364	    (string-to-number (match-string 3 s))
12365	    (string-to-number (match-string 2 s))
12366	    nil nil nil)
12367    (make-list 9 0)))
12368
12369(defun org-timestamp-up (&optional arg)
12370  "Increase the date item at the cursor by one.
12371If the cursor is on the year, change the year.  If it is on the month or
12372the day, change that.
12373With prefix ARG, change by that many units."
12374  (interactive "p")
12375  (org-timestamp-change (prefix-numeric-value arg)))
12376
12377(defun org-timestamp-down (&optional arg)
12378  "Decrease the date item at the cursor by one.
12379If the cursor is on the year, change the year.  If it is on the month or
12380the day, change that.
12381With prefix ARG, change by that many units."
12382  (interactive "p")
12383  (org-timestamp-change (- (prefix-numeric-value arg))))
12384
12385(defun org-timestamp-up-day (&optional arg)
12386  "Increase the date in the time stamp by one day.
12387With prefix ARG, change that many days."
12388  (interactive "p")
12389  (if (and (not (org-at-timestamp-p t))
12390	   (org-on-heading-p))
12391      (org-todo 'up)
12392    (org-timestamp-change (prefix-numeric-value arg) 'day)))
12393
12394(defun org-timestamp-down-day (&optional arg)
12395  "Decrease the date in the time stamp by one day.
12396With prefix ARG, change that many days."
12397  (interactive "p")
12398  (if (and (not (org-at-timestamp-p t))
12399	   (org-on-heading-p))
12400      (org-todo 'down)
12401    (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12402
12403(defsubst org-pos-in-match-range (pos n)
12404  (and (match-beginning n)
12405       (<= (match-beginning n) pos)
12406       (>= (match-end n) pos)))
12407
12408(defun org-at-timestamp-p (&optional inactive-ok)
12409  "Determine if the cursor is in or at a timestamp."
12410  (interactive)
12411  (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12412	 (pos (point))
12413	 (ans (or (looking-at tsr)
12414		  (save-excursion
12415		    (skip-chars-backward "^[<\n\r\t")
12416		    (if (> (point) 1) (backward-char 1))
12417		    (and (looking-at tsr)
12418			 (> (- (match-end 0) pos) -1))))))
12419    (and (boundp 'org-ts-what)
12420	 (setq org-ts-what
12421	      (cond
12422	       ((org-pos-in-match-range pos 2)      'year)
12423	       ((org-pos-in-match-range pos 3)      'month)
12424	       ((org-pos-in-match-range pos 7)      'hour)
12425	       ((org-pos-in-match-range pos 8)      'minute)
12426	       ((or (org-pos-in-match-range pos 4)
12427		    (org-pos-in-match-range pos 5)) 'day)
12428	       (t 'day))))
12429    ans))
12430
12431(defun org-timestamp-change (n &optional what)
12432  "Change the date in the time stamp at point.
12433The date will be changed by N times WHAT.  WHAT can be `day', `month',
12434`year', `minute', `second'.  If WHAT is not given, the cursor position
12435in the timestamp determines what will be changed."
12436  (let ((pos (point))
12437	with-hm inactive
12438	org-ts-what
12439	ts time time0)
12440    (if (not (org-at-timestamp-p t))
12441	(error "Not at a timestamp"))
12442    (if (and (not what) (not (eq org-ts-what 'day))
12443	     org-display-custom-times
12444	     (get-text-property (point) 'display)
12445	     (not (get-text-property (1- (point)) 'display)))
12446	(setq org-ts-what 'day))
12447    (setq org-ts-what (or what org-ts-what)
12448	  with-hm (<= (abs (- (cdr org-ts-lengths)
12449			      (- (match-end 0) (match-beginning 0))))
12450		      1)
12451	  inactive (= (char-after (match-beginning 0)) ?\[)
12452	  ts (match-string 0))
12453    (replace-match "")
12454    (setq time0 (org-parse-time-string ts))
12455    (setq time
12456	  (apply 'encode-time
12457		 (append
12458		  (list (or (car time0) 0))
12459		  (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
12460		  (list (+ (if (eq org-ts-what 'hour) n 0)   (nth 2 time0)))
12461		  (list (+ (if (eq org-ts-what 'day) n 0)    (nth 3 time0)))
12462		  (list (+ (if (eq org-ts-what 'month) n 0)  (nth 4 time0)))
12463		  (list (+ (if (eq org-ts-what 'year) n 0)   (nth 5 time0)))
12464		  (nthcdr 6 time0))))
12465    (if (eq what 'calendar)
12466	(let ((cal-date
12467	       (save-excursion
12468		 (save-match-data
12469		   (set-buffer "*Calendar*")
12470		   (calendar-cursor-to-date)))))
12471	  (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12472	  (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12473	  (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12474	  (setcar time0 (or (car time0) 0))
12475	  (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12476	  (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
12477	  (setq time (apply 'encode-time time0))))
12478    (setq org-last-changed-timestamp
12479	  (org-insert-time-stamp time with-hm inactive))
12480    (org-clock-update-time-maybe)
12481    (goto-char pos)
12482    ;; Try to recenter the calendar window, if any
12483    (if (and org-calendar-follow-timestamp-change
12484	     (get-buffer-window "*Calendar*" t)
12485	     (memq org-ts-what '(day month year)))
12486	(org-recenter-calendar (time-to-days time)))))
12487
12488(defun org-recenter-calendar (date)
12489  "If the calendar is visible, recenter it to DATE."
12490  (let* ((win (selected-window))
12491	 (cwin (get-buffer-window "*Calendar*" t))
12492	 (calendar-move-hook nil))
12493    (when cwin
12494      (select-window cwin)
12495      (calendar-goto-date (if (listp date) date
12496			    (calendar-gregorian-from-absolute date)))
12497      (select-window win))))
12498
12499(defun org-goto-calendar (&optional arg)
12500  "Go to the Emacs calendar at the current date.
12501If there is a time stamp in the current line, go to that date.
12502A prefix ARG can be used to force the current date."
12503  (interactive "P")
12504  (let ((tsr org-ts-regexp) diff
12505	(calendar-move-hook nil)
12506	(view-calendar-holidays-initially nil)
12507	(view-diary-entries-initially nil))
12508    (if (or (org-at-timestamp-p)
12509	    (save-excursion
12510	      (beginning-of-line 1)
12511	      (looking-at (concat ".*" tsr))))
12512	(let ((d1 (time-to-days (current-time)))
12513	      (d2 (time-to-days
12514		   (org-time-string-to-time (match-string 1)))))
12515	  (setq diff (- d2 d1))))
12516    (calendar)
12517    (calendar-goto-today)
12518    (if (and diff (not arg)) (calendar-forward-day diff))))
12519
12520(defun org-date-from-calendar ()
12521  "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12522If there is already a time stamp at the cursor position, update it."
12523  (interactive)
12524  (org-timestamp-change 0 'calendar))
12525
12526;;; The clock for measuring work time.
12527
12528(defvar org-clock-marker (make-marker)
12529  "Marker recording the last clock-in.")
12530
12531(defun org-clock-in ()
12532  "Start the clock on the current item.
12533If necessary, clock-out of the currently active clock."
12534  (interactive)
12535  (org-clock-out t)
12536  (let (ts)
12537    (save-excursion
12538      (org-back-to-heading t)
12539      (beginning-of-line 2)
12540      (when (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
12541		 (not (equal (match-string 1) org-clock-string)))
12542	;; First line hast scheduling info, move one further
12543	(beginning-of-line 2)
12544	(or (bolp) (newline)))
12545      (insert "\n") (backward-char 1)
12546      (indent-relative)
12547      (insert org-clock-string " ")
12548      (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
12549      (move-marker org-clock-marker (point) (buffer-base-buffer))
12550      (message "Clock started at %s" ts))))
12551
12552(defun org-clock-out (&optional fail-quietly)
12553  "Stop the currently running clock.
12554If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
12555  (interactive)
12556  (catch 'exit
12557  (if (not (marker-buffer org-clock-marker))
12558      (if fail-quietly (throw 'exit t) (error "No active clock")))
12559  (let (ts te s h m)
12560    (save-excursion
12561      (set-buffer (marker-buffer org-clock-marker))
12562      (goto-char org-clock-marker)
12563      (beginning-of-line 1)
12564      (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
12565	       (equal (match-string 1) org-clock-string))
12566	  (setq ts (match-string 2))
12567	(if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
12568      (goto-char org-clock-marker)
12569      (insert "--")
12570      (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
12571      (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
12572		 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
12573	    h (floor (/ s 3600))
12574	    s (- s (* 3600 h))
12575	    m (floor (/ s 60))
12576	    s (- s (* 60 s)))
12577      (insert " => " (format "%2d:%02d" h m))
12578      (move-marker org-clock-marker nil)
12579      (org-add-log-maybe 'clock-out)
12580      (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
12581
12582(defun org-clock-cancel ()
12583  "Cancel the running clock be removing the start timestamp."
12584  (interactive)
12585  (if (not (marker-buffer org-clock-marker))
12586      (error "No active clock"))
12587  (save-excursion
12588    (set-buffer (marker-buffer org-clock-marker))
12589    (goto-char org-clock-marker)
12590    (delete-region (1- (point-at-bol)) (point-at-eol)))
12591  (message "Clock canceled"))
12592
12593(defvar org-clock-file-total-minutes nil
12594  "Holds the file total time in minutes, after a call to `org-clock-sum'.")
12595  (make-variable-buffer-local 'org-clock-file-total-minutes)
12596
12597(defun org-clock-sum (&optional tstart tend)
12598  "Sum the times for each subtree.
12599Puts the resulting times in minutes as a text property on each headline."
12600  (interactive)
12601  (let* ((bmp (buffer-modified-p))
12602	 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
12603		     org-clock-string
12604		     "[ \t]*\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)"))
12605	 (lmax 30)
12606	 (ltimes (make-vector lmax 0))
12607	 (t1 0)
12608	 (level 0)
12609	 ts te dt
12610	 time)
12611    (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
12612    (save-excursion
12613      (goto-char (point-max))
12614      (while (re-search-backward re nil t)
12615	(if (match-end 2)
12616	    ;; A time
12617	    (setq ts (match-string 2)
12618		  te (match-string 3)
12619		  ts (time-to-seconds
12620		      (apply 'encode-time (org-parse-time-string ts)))
12621		  te (time-to-seconds
12622		      (apply 'encode-time (org-parse-time-string te)))
12623		  ts (if tstart (max ts tstart) ts)
12624		  te (if tend (min te tend) te)
12625		  dt (- te ts)
12626		  t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1))
12627	  ;; A headline
12628	  (setq level (- (match-end 1) (match-beginning 1)))
12629	  (when (or (> t1 0) (> (aref ltimes level) 0))
12630	    (loop for l from 0 to level do
12631		  (aset ltimes l (+ (aref ltimes l) t1)))
12632	    (setq t1 0 time (aref ltimes level))
12633	    (loop for l from level to (1- lmax) do
12634		  (aset ltimes l 0))
12635	    (goto-char (match-beginning 0))
12636	    (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
12637      (setq org-clock-file-total-minutes (aref ltimes 0)))
12638    (set-buffer-modified-p bmp)))
12639
12640(defun org-clock-display (&optional total-only)
12641  "Show subtree times in the entire buffer.
12642If TOTAL-ONLY is non-nil, only show the total time for the entire file
12643in the echo area."
12644  (interactive)
12645  (org-remove-clock-overlays)
12646  (let (time h m p)
12647    (org-clock-sum)
12648    (unless total-only
12649      (save-excursion
12650	(goto-char (point-min))
12651	(while (setq p (next-single-property-change (point) :org-clock-minutes))
12652	  (goto-char p)
12653	  (when (setq time (get-text-property p :org-clock-minutes))
12654	    (org-put-clock-overlay time (funcall outline-level))))
12655	(setq h (/ org-clock-file-total-minutes 60)
12656	      m (- org-clock-file-total-minutes (* 60 h)))
12657	;; Arrange to remove the overlays upon next change.
12658	(when org-remove-highlights-with-change
12659	  (org-add-hook 'before-change-functions 'org-remove-clock-overlays
12660			nil 'local))))
12661    (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
12662
12663(defvar org-clock-overlays nil)
12664(make-variable-buffer-local 'org-clock-overlays)
12665
12666(defun org-put-clock-overlay (time &optional level)
12667  "Put an overlays on the current line, displaying TIME.
12668If LEVEL is given, prefix time with a corresponding number of stars.
12669This creates a new overlay and stores it in `org-clock-overlays', so that it
12670will be easy to remove."
12671  (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
12672	 (l (if level (org-get-legal-level level 0) 0))
12673	 (off 0)
12674	 ov tx)
12675    (move-to-column c)
12676    (unless (eolp) (skip-chars-backward "^ \t"))
12677    (skip-chars-backward " \t")
12678    (setq ov (org-make-overlay (1- (point)) (point-at-eol))
12679	  tx (concat (buffer-substring (1- (point)) (point))
12680		     (make-string (+ off (max 0 (- c (current-column)))) ?.)
12681		     (org-add-props (format "%s %2d:%02d%s"
12682					    (make-string l ?*) h m
12683					    (make-string (- 10 l) ?\ ))
12684			 '(face secondary-selection))
12685		     ""))
12686    (if (not (featurep 'xemacs))
12687	(org-overlay-put ov 'display tx)
12688      (org-overlay-put ov 'invisible t)
12689      (org-overlay-put ov 'end-glyph (make-glyph tx)))
12690    (push ov org-clock-overlays)))
12691
12692(defun org-remove-clock-overlays (&optional beg end noremove)
12693  "Remove the occur highlights from the buffer.
12694BEG and END are ignored.  If NOREMOVE is nil, remove this function
12695from the `before-change-functions' in the current buffer."
12696  (interactive)
12697  (unless org-inhibit-highlight-removal
12698    (mapc 'org-delete-overlay org-clock-overlays)
12699    (setq org-clock-overlays nil)
12700    (unless noremove
12701      (remove-hook 'before-change-functions
12702		   'org-remove-clock-overlays 'local))))
12703
12704(defun org-clock-out-if-current ()
12705  "Clock out if the current entry contains the running clock.
12706This is used to stop the clock after a TODO entry is marked DONE."
12707  (when (and (equal state org-done-string)
12708	     (equal (marker-buffer org-clock-marker) (current-buffer))
12709	     (< (point) org-clock-marker)
12710	     (> (save-excursion (outline-next-heading) (point))
12711		org-clock-marker))
12712    ;; Clock out, but don't accept a logging message for this.
12713    (let ((org-log-done (if (and (listp org-log-done)
12714				 (member 'clock-out org-log-done))
12715			    '(done)
12716			  org-log-done)))
12717      (org-clock-out))))
12718
12719(add-hook 'org-after-todo-state-change-hook
12720	  'org-clock-out-if-current)
12721
12722(defun org-check-running-clock ()
12723  "Check if the current buffer contains the running clock.
12724If yes, offer to stop it and to save the buffer with the changes."
12725  (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
12726	     (y-or-n-p (format "Clock-out in buffer %s before killing it? "
12727			       (buffer-name))))
12728    (org-clock-out)
12729    (when (y-or-n-p "Save changed buffer?")
12730      (save-buffer))))
12731
12732(defun org-clock-report ()
12733  "Create a table containing a report about clocked time.
12734If the buffer contains lines
12735#+BEGIN: clocktable :maxlevel 3 :emphasize nil
12736
12737#+END: clocktable
12738then the table will be inserted between these lines, replacing whatever
12739is was there before.  If these lines are not in the buffer, the table
12740is inserted at point, surrounded by the special lines.
12741The BEGIN line can contain parameters.  Allowed are:
12742:maxlevel   The maximum level to be included in the table.  Default is 3.
12743:emphasize  t/nil, if levell 1 and level 2 should be bold/italic in the table."
12744  (interactive)
12745  (org-remove-clock-overlays)
12746  (unless (org-find-dblock "clocktable")
12747    (org-create-dblock (list :name "clocktable"
12748			     :maxlevel 2 :emphasize nil)))
12749  (org-update-dblock))
12750
12751(defun org-clock-update-time-maybe ()
12752  "If this is a CLOCK line, update it and return t.
12753Otherwise, return nil."
12754  (interactive)
12755  (save-excursion
12756    (beginning-of-line 1)
12757    (skip-chars-forward " \t")
12758    (when (looking-at org-clock-string)
12759      (let ((re (concat "[ \t]*" org-clock-string
12760			" *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
12761			"\\([ \t]*=>.*\\)?"))
12762	    ts te h m s)
12763	(if (not (looking-at re))
12764	    nil
12765	  (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
12766	  (end-of-line 1)
12767	  (setq ts (match-string 1)
12768		te (match-string 2))
12769	  (setq s (- (time-to-seconds
12770		      (apply 'encode-time (org-parse-time-string te)))
12771		     (time-to-seconds
12772		      (apply 'encode-time (org-parse-time-string ts))))
12773		h (floor (/ s 3600))
12774		s (- s (* 3600 h))
12775		m (floor (/ s 60))
12776		s (- s (* 60 s)))
12777	  (insert " => " (format "%2d:%02d" h m))
12778	  t)))))
12779
12780(defun org-clock-special-range (key &optional time as-strings)
12781  "Return two times bordering a special time range.
12782Key is a symbol specifying the range and can be one of `today', `yesterday',
12783`thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
12784A week starts Monday 0:00 and ends Sunday 24:00.
12785The range is determined relative to TIME.  TIME defaults to the current time.
12786The return value is a cons cell with two internal times like the ones
12787returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
12788the returned times will be formatted strings."
12789  (let* ((tm (decode-time (or time (current-time))))
12790	 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
12791	 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
12792	 (dow (nth 6 tm))
12793	 s1 m1 h1 d1 month1 y1 diff ts te fm)
12794    (cond
12795     ((eq key 'today)
12796      (setq h 0 m 0 h1 24 m1 0))
12797     ((eq key 'yesterday)
12798      (setq d (1- d) h 0 m 0 h1 24 m1 0))
12799     ((eq key 'thisweek)
12800      (setq diff (if (= dow 0) 6 (1- dow))
12801	    m 0 h 0 d (- d diff) d1 (+ 7 d)))
12802     ((eq key 'lastweek)
12803      (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
12804	    m 0 h 0 d (- d diff) d1 (+ 7 d)))
12805     ((eq key 'thismonth)
12806      (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
12807     ((eq key 'lastmonth)
12808      (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
12809     ((eq key 'thisyear)
12810      (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
12811     ((eq key 'lastyear)
12812      (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
12813     (t (error "No such time block %s" key)))
12814    (setq ts (encode-time s m h d month y)
12815	  te (encode-time (or s1 s) (or m1 m) (or h1 h)
12816			  (or d1 d) (or month1 month) (or y1 y)))
12817    (setq fm (cdr org-time-stamp-formats))
12818    (if as-strings
12819	(cons (format-time-string fm ts) (format-time-string fm te))
12820      (cons ts te))))
12821
12822(defun org-dblock-write:clocktable (params)
12823  "Write the standard clocktable."
12824  (let ((hlchars '((1 . "*") (2 . ?/)))
12825	(emph nil)
12826	(ins (make-marker))
12827	ipos time h m p level hlc hdl maxlevel
12828	ts te cc block)
12829    (setq maxlevel (or (plist-get params :maxlevel) 3)
12830	  emph (plist-get params :emphasize)
12831	  ts (plist-get params :tstart)
12832	  te (plist-get params :tend)
12833	  block (plist-get params :block))
12834    (when block
12835      (setq cc (org-clock-special-range block nil t)
12836	    ts (car cc) te (cdr cc)))
12837    (if ts (setq ts (time-to-seconds
12838		     (apply 'encode-time (org-parse-time-string ts)))))
12839    (if te (setq te (time-to-seconds
12840		     (apply 'encode-time (org-parse-time-string te)))))
12841    (move-marker ins (point))
12842    (setq ipos (point))
12843    (insert-before-markers "Clock summary at ["
12844			   (substring
12845			    (format-time-string (cdr org-time-stamp-formats))
12846			    1 -1)
12847			   "]."
12848			   (if block
12849			       (format "  Considered range is /%s/." block)
12850			     "")
12851			   "\n\n|L|Headline|Time|\n")
12852    (org-clock-sum ts te)
12853    (setq h (/ org-clock-file-total-minutes 60)
12854	  m (- org-clock-file-total-minutes (* 60 h)))
12855    (insert-before-markers "|-\n|0|" "*Total file time*| "
12856			   (format "*%d:%02d*" h m)
12857			   "|\n")
12858    (goto-char (point-min))
12859    (while (setq p (next-single-property-change (point) :org-clock-minutes))
12860      (goto-char p)
12861      (when (setq time (get-text-property p :org-clock-minutes))
12862	(save-excursion
12863	  (beginning-of-line 1)
12864	  (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
12865		     (setq level (- (match-end 1) (match-beginning 1)))
12866		     (<= level maxlevel))
12867	    (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
12868		  hdl (match-string 2)
12869		  h (/ time 60)
12870		  m (- time (* 60 h)))
12871	    (goto-char ins)
12872	    (if (= level 1) (insert-before-markers "|-\n"))
12873	    (insert-before-markers
12874	     "| " (int-to-string level) "|" hlc hdl hlc " |"
12875	     (make-string (1- level) ?|)
12876	     hlc
12877	     (format "%d:%02d" h m)
12878	     hlc
12879	     " |\n")))))
12880    (goto-char ins)
12881    (backward-delete-char 1)
12882    (goto-char ipos)
12883    (skip-chars-forward "^|")
12884    (org-table-align)))
12885
12886;; FIXME: I don't think anybody uses this, ask David
12887(defun org-collect-clock-time-entries ()
12888  "Return an internal list with clocking information.
12889This list has one entry for each CLOCK interval.
12890FIXME: describe the elements."
12891  (interactive)
12892  (let ((re (concat "^[ \t]*" org-clock-string
12893		    " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
12894	rtn beg end next cont level title total closedp leafp
12895	clockpos titlepos h m donep)
12896    (save-excursion
12897      (org-clock-sum)
12898      (goto-char (point-min))
12899      (while (re-search-forward re nil t)
12900	(setq clockpos (match-beginning 0)
12901	      beg (match-string 1) end (match-string 2)
12902	      cont (match-end 0))
12903	(setq beg (apply 'encode-time (org-parse-time-string beg))
12904	      end (apply 'encode-time (org-parse-time-string end)))
12905	(org-back-to-heading t)
12906	(setq donep (org-entry-is-done-p))
12907	(setq titlepos (point)
12908	      total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
12909	      h (/ total 60) m (- total (* 60 h))
12910	      total (cons h m))
12911	(looking-at "\\(\\*+\\) +\\(.*\\)")
12912	(setq level (- (match-end 1) (match-beginning 1))
12913	      title (org-match-string-no-properties 2))
12914	(save-excursion (outline-next-heading) (setq next (point)))
12915	(setq closedp (re-search-forward org-closed-time-regexp next t))
12916	(goto-char next)
12917	(setq leafp (and (looking-at "^\\*+ ")
12918			 (<= (- (match-end 0) (point)) level)))
12919	(push (list beg end clockpos closedp donep
12920		    total title titlepos level leafp)
12921	      rtn)
12922	(goto-char cont)))
12923    (nreverse rtn)))
12924
12925;;;; Agenda, and Diary Integration
12926
12927;;; Define the Org-agenda-mode
12928
12929(defvar org-agenda-mode-map (make-sparse-keymap)
12930  "Keymap for `org-agenda-mode'.")
12931
12932(defvar org-agenda-menu) ; defined later in this file.
12933(defvar org-agenda-follow-mode nil)
12934(defvar org-agenda-show-log nil)
12935(defvar org-agenda-redo-command nil)
12936(defvar org-agenda-mode-hook nil)
12937(defvar org-agenda-type nil)
12938(defvar org-agenda-force-single-file nil)
12939
12940(defun org-agenda-mode ()
12941  "Mode for time-sorted view on action items in Org-mode files.
12942
12943The following commands are available:
12944
12945\\{org-agenda-mode-map}"
12946  (interactive)
12947  (kill-all-local-variables)
12948  (setq org-agenda-undo-list nil
12949	org-agenda-pending-undo-list nil)
12950  (setq major-mode 'org-agenda-mode)
12951  ;; Keep global-font-lock-mode from turning on font-lock-mode
12952  (org-set-local 'font-lock-global-modes (list 'not major-mode))
12953  (setq mode-name "Org-Agenda")
12954  (use-local-map org-agenda-mode-map)
12955  (easy-menu-add org-agenda-menu)
12956  (if org-startup-truncated (setq truncate-lines t))
12957  (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
12958  (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
12959  ;; Make sure properties are removed when copying text
12960  (when (boundp 'buffer-substring-filters)
12961    (org-set-local 'buffer-substring-filters
12962		   (cons (lambda (x)
12963                           (set-text-properties 0 (length x) nil x) x)
12964			 buffer-substring-filters)))
12965  (unless org-agenda-keep-modes
12966    (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
12967	  org-agenda-show-log nil))
12968  (easy-menu-change
12969   '("Agenda") "Agenda Files"
12970   (append
12971    (list
12972     (vector
12973      (if (get 'org-agenda-files 'org-restrict)
12974	  "Restricted to single file"
12975	"Edit File List")
12976      '(org-edit-agenda-file-list)
12977      (not (get 'org-agenda-files 'org-restrict)))
12978     "--")
12979    (mapcar 'org-file-menu-entry (org-agenda-files))))
12980  (org-agenda-set-mode-name)
12981  (apply
12982   (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
12983   (list 'org-agenda-mode-hook)))
12984
12985(substitute-key-definition 'undo 'org-agenda-undo
12986			   org-agenda-mode-map global-map)
12987(define-key org-agenda-mode-map "\C-i"     'org-agenda-goto)
12988(define-key org-agenda-mode-map [(tab)]    'org-agenda-goto)
12989(define-key org-agenda-mode-map "\C-m"     'org-agenda-switch-to)
12990(define-key org-agenda-mode-map "\C-k"     'org-agenda-kill)
12991(define-key org-agenda-mode-map "\C-c$"    'org-agenda-archive)
12992(define-key org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
12993(define-key org-agenda-mode-map "$"        'org-agenda-archive)
12994(define-key org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
12995(define-key org-agenda-mode-map " "        'org-agenda-show)
12996(define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
12997(define-key org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
12998(define-key org-agenda-mode-map "b"        'org-agenda-tree-to-indirect-buffer)
12999(define-key org-agenda-mode-map "o"        'delete-other-windows)
13000(define-key org-agenda-mode-map "L"        'org-agenda-recenter)
13001(define-key org-agenda-mode-map "t"        'org-agenda-todo)
13002(define-key org-agenda-mode-map "a"        'org-agenda-toggle-archive-tag)
13003(define-key org-agenda-mode-map ":"        'org-agenda-set-tags)
13004(define-key org-agenda-mode-map "."        'org-agenda-goto-today)
13005(define-key org-agenda-mode-map "d"        'org-agenda-day-view)
13006(define-key org-agenda-mode-map "w"        'org-agenda-week-view)
13007(define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
13008(define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
13009(define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
13010(define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
13011
13012(define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
13013(define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
13014(define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
13015(let ((l '(1 2 3 4 5 6 7 8 9 0)))
13016  (while l (define-key org-agenda-mode-map
13017	     (int-to-string (pop l)) 'digit-argument)))
13018
13019(define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
13020(define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
13021(define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
13022(define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
13023(define-key org-agenda-mode-map "r" 'org-agenda-redo)
13024(define-key org-agenda-mode-map "q" 'org-agenda-quit)
13025(define-key org-agenda-mode-map "x" 'org-agenda-exit)
13026(define-key org-agenda-mode-map "s" 'org-save-all-org-buffers)
13027(define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
13028(define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
13029(define-key org-agenda-mode-map "n" 'next-line)
13030(define-key org-agenda-mode-map "p" 'previous-line)
13031(define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
13032(define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
13033(define-key org-agenda-mode-map "," 'org-agenda-priority)
13034(define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
13035(define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
13036(define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
13037(eval-after-load "calendar"
13038  '(define-key calendar-mode-map org-calendar-to-agenda-key
13039     'org-calendar-goto-agenda))
13040(define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
13041(define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
13042(define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
13043(define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
13044(define-key org-agenda-mode-map "h" 'org-agenda-holidays)
13045(define-key org-agenda-mode-map "H" 'org-agenda-holidays)
13046(define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
13047(define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
13048(define-key org-agenda-mode-map "O" 'org-agenda-clock-out)
13049(define-key org-agenda-mode-map "X" 'org-agenda-clock-cancel)
13050(define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
13051(define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
13052(define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
13053(define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
13054(define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
13055(define-key org-agenda-mode-map [(right)] 'org-agenda-later)
13056(define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
13057(define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
13058(defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
13059  "Local keymap for agenda entries from Org-mode.")
13060
13061(define-key org-agenda-keymap
13062  (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
13063(define-key org-agenda-keymap
13064  (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
13065(when org-agenda-mouse-1-follows-link
13066  (define-key org-agenda-keymap [follow-link] 'mouse-face))
13067(easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
13068  '("Agenda"
13069    ("Agenda Files")
13070    "--"
13071    ["Show" org-agenda-show t]
13072    ["Go To (other window)" org-agenda-goto t]
13073    ["Go To (this window)" org-agenda-switch-to t]
13074    ["Follow Mode" org-agenda-follow-mode
13075     :style toggle :selected org-agenda-follow-mode :active t]
13076    ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
13077    "--"
13078    ["Cycle TODO" org-agenda-todo t]
13079    ["Archive subtree" org-agenda-archive t]
13080    ["Delete subtree" org-agenda-kill t]
13081    "--"
13082    ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
13083    ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
13084    ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
13085    "--"
13086    ("Tags"
13087     ["Show all Tags" org-agenda-show-tags t]
13088     ["Set Tags" org-agenda-set-tags t])
13089    ("Date/Schedule"
13090     ["Schedule" org-agenda-schedule t]
13091     ["Set Deadline" org-agenda-deadline t]
13092     "--"
13093     ["Change date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
13094     ["Change date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
13095     ["Change date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
13096    ("Priority"
13097     ["Set Priority" org-agenda-priority t]
13098     ["Increase Priority" org-agenda-priority-up t]
13099     ["Decrease Priority" org-agenda-priority-down t]
13100     ["Show Priority" org-agenda-show-priority t])
13101    ("Calendar/Diary"
13102     ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
13103     ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
13104     ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
13105     ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
13106     ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
13107     ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
13108     "--"
13109     ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
13110    "--"
13111    ("View"
13112     ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
13113      :style radio :selected (equal org-agenda-ndays 1)]
13114     ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
13115      :style radio :selected (equal org-agenda-ndays 7)]
13116     "--"
13117     ["Show Logbook entries" org-agenda-log-mode
13118      :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
13119     ["Include Diary" org-agenda-toggle-diary
13120      :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
13121     ["Use Time Grid" org-agenda-toggle-time-grid
13122      :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
13123    ["Rebuild buffer" org-agenda-redo t]
13124    ["Save all Org-mode Buffers" org-save-all-org-buffers t]
13125    "--"
13126    ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
13127    "--"
13128    ["Quit" org-agenda-quit t]
13129    ["Exit and Release Buffers" org-agenda-exit t]
13130    ))
13131
13132;;; Agenda undo
13133
13134(defvar org-agenda-allow-remote-undo t
13135  "Non-nil means, allow remote undo from the agenda buffer.")
13136(defvar org-agenda-undo-list nil
13137  "List of undoable operations in the agenda since last refresh.")
13138(defvar org-agenda-undo-has-started-in nil
13139  "Buffers that have already seen `undo-start' in the current undo sequence.")
13140(defvar org-agenda-pending-undo-list nil
13141  "In a series of undo commands, this is the list of remaning undo items.")
13142
13143(defmacro org-if-unprotected (&rest body)
13144  "Execute BODY if ther is no `org-protected' text property at point."
13145  (declare (debug t))
13146  `(unless (get-text-property (point) 'org-protected)
13147     ,@body))
13148
13149(defmacro org-with-remote-undo (_buffer &rest _body)
13150  "Execute BODY while recording undo information in two buffers."
13151  (declare (indent 1) (debug t))
13152  `(let ((_cline (org-current-line))
13153	 (_cmd this-command)
13154	 (_buf1 (current-buffer))
13155	 (_buf2 ,_buffer)
13156	 (_undo1 buffer-undo-list)
13157	 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
13158	 _c1 _c2)
13159     ,@_body
13160     (when org-agenda-allow-remote-undo
13161       (setq _c1 (org-verify-change-for-undo
13162		  _undo1 (with-current-buffer _buf1 buffer-undo-list))
13163	     _c2 (org-verify-change-for-undo
13164		  _undo2 (with-current-buffer _buf2 buffer-undo-list)))
13165       (when (or _c1 _c2)
13166	 ;; make sure there are undo boundaries
13167	 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
13168	 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
13169	 ;; remember which buffer to undo
13170	 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
13171	       org-agenda-undo-list)))))
13172
13173(defun org-agenda-undo ()
13174  "Undo a remote editing step in the agenda.
13175This undoes changes both in the agenda buffer and in the remote buffer
13176that have been changed along."
13177  (interactive)
13178  (or org-agenda-allow-remote-undo
13179      (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
13180  (if (not (eq this-command last-command))
13181      (setq org-agenda-undo-has-started-in nil
13182	    org-agenda-pending-undo-list org-agenda-undo-list))
13183  (if (not org-agenda-pending-undo-list)
13184      (error "No further undo information"))
13185  (let* ((entry (pop org-agenda-pending-undo-list))
13186	 buf line cmd rembuf)
13187    (setq cmd (pop entry) line (pop entry))
13188    (setq rembuf (nth 2 entry))
13189    (org-with-remote-undo rembuf
13190      (while (bufferp (setq buf (pop entry)))
13191	(if (pop entry)
13192	    (with-current-buffer buf
13193	      (let ((last-undo-buffer buf)
13194                    buffer-read-only)
13195		(unless (memq buf org-agenda-undo-has-started-in)
13196		  (push buf org-agenda-undo-has-started-in)
13197		  (make-local-variable 'pending-undo-list)
13198		  (undo-start))
13199		(while (and pending-undo-list
13200			    (listp pending-undo-list)
13201			    (not (car pending-undo-list)))
13202		  (pop pending-undo-list))
13203		(undo-more 1))))))
13204    (goto-line line)
13205    (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
13206
13207(defun org-verify-change-for-undo (l1 l2)
13208  "Verify that a real change occurred between the undo lists L1 and L2."
13209  (while (and l1 (listp l1) (null (car l1))) (pop l1))
13210  (while (and l2 (listp l2) (null (car l2))) (pop l2))
13211  (not (eq l1 l2)))
13212
13213;;; Agenda dispatch
13214
13215(defvar org-agenda-restrict nil)
13216(defvar org-agenda-restrict-begin (make-marker))
13217(defvar org-agenda-restrict-end (make-marker))
13218(defvar org-agenda-last-dispatch-buffer nil)
13219
13220;;;###autoload
13221(defun org-agenda (arg)
13222  "Dispatch agenda commands to collect entries to the agenda buffer.
13223Prompts for a character to select a command.  Any prefix arg will be passed
13224on to the selected command.  The default selections are:
13225g
13226a     Call `org-agenda-list' to display the agenda for current day or week.
13227t     Call `org-todo-list' to display the global todo list.
13228T     Call `org-todo-list' to display the global todo list, select only
13229      entries with a specific TODO keyword (the user gets a prompt).
13230m     Call `org-tags-view' to display headlines with tags matching
13231      a condition  (the user is prompted for the condition).
13232M     Like `m', but select only TODO entries, no ordinary headlines.
13233l     Create a timeeline for the current buffer.
13234
13235More commands can be added by configuring the variable
13236`org-agenda-custom-commands'.  In particular, specific tags and TODO keyword
13237searches can be pre-defined in this way.
13238
13239If the current buffer is in Org-mode and visiting a file, you can also
13240first press `1' to indicate that the agenda should be temporarily (until the
13241next use of \\[org-agenda]) restricted to the current file."
13242  (interactive "P")
13243  (catch 'exit
13244    (let* ((buf (current-buffer))
13245	   (bfn (buffer-file-name (buffer-base-buffer)))
13246	   (restrict-ok (and bfn (org-mode-p)))
13247	   (custom org-agenda-custom-commands)
13248	   c entry key type match lprops)
13249      ;; Turn off restriction
13250      (put 'org-agenda-files 'org-restrict nil)
13251      (setq org-agenda-restrict nil)
13252      (move-marker org-agenda-restrict-begin nil)
13253      (move-marker org-agenda-restrict-end nil)
13254      ;; Remember where this call originated
13255      (setq org-agenda-last-dispatch-buffer (current-buffer))
13256      (save-window-excursion
13257	(delete-other-windows)
13258	(switch-to-buffer-other-window " *Agenda Commands*")
13259	(erase-buffer)
13260	(insert (eval-when-compile
13261		  (let ((header
13262"Press key for an agenda command:
13263--------------------------------         C   Configure custom agenda commands
13264a   Agenda for current week or day
13265t   List of all TODO entries             T   Entries with special TODO kwd
13266m   Match a TAGS query                   M   Like m, but only TODO entries
13267L   Timeline for current buffer          #   List stuck projects (!=configure)
13268")
13269			(start 0))
13270		    (while (string-match "\\(^\\|   \\|(\\)\\(\\S-\\)\\( \\|=\\)" header start)
13271		      (setq start (match-end 0))
13272		      (add-text-properties (match-beginning 2) (match-end 2)
13273					   '(face bold) header))
13274		    header)))
13275	(while (setq entry (pop custom))
13276	  (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
13277	  (insert (format "\n%-4s%-14s: %s"
13278			  (org-add-props (copy-sequence key)
13279			      '(face bold))
13280			  (cond
13281			   ((stringp type) type)
13282			   ((eq type 'todo) "TODO keyword")
13283			   ((eq type 'tags) "Tags query")
13284			   ((eq type 'tags-todo) "Tags (TODO)")
13285			   ((eq type 'tags-tree) "Tags tree")
13286			   ((eq type 'todo-tree) "TODO kwd tree")
13287			   ((eq type 'occur-tree) "Occur tree")
13288			   ((functionp type) (symbol-name type))
13289			   (t "???"))
13290			  (if (stringp match)
13291			      (org-add-props match nil 'face 'org-warning)
13292			    (format "set of %d commands" (length match))))))
13293	(if restrict-ok
13294	    (insert "\n"
13295		    (org-add-props "1   Restrict call to current buffer      0   Restrict call to region or subtree" nil 'face 'org-table)))
13296	(goto-char (point-min))
13297	(if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
13298	(message "Press key for agenda command%s"
13299		 (if restrict-ok ", or [1] or [0] to restrict" ""))
13300	(setq c (read-char-exclusive))
13301	(message "")
13302	(when (memq c '(?L ?1 ?0))
13303	  (if restrict-ok
13304	      (put 'org-agenda-files 'org-restrict (list bfn))
13305	    (error "Cannot restrict agenda to current buffer"))
13306	  (with-current-buffer " *Agenda Commands*"
13307	    (goto-char (point-max))
13308	    (delete-region (point-at-bol) (point))
13309	    (goto-char (point-min)))
13310	  (when (eq c ?0)
13311	    (setq org-agenda-restrict t)
13312	    (with-current-buffer buf
13313	      (if (org-region-active-p)
13314		  (progn
13315		    (move-marker org-agenda-restrict-begin (region-beginning))
13316		    (move-marker org-agenda-restrict-end (region-end)))
13317		(save-excursion
13318		  (org-back-to-heading t)
13319		  (move-marker org-agenda-restrict-begin (point))
13320		  (move-marker org-agenda-restrict-end
13321			       (progn (org-end-of-subtree t)))))))
13322	  (unless (eq c ?L)
13323	    (message "Press key for agenda command%s"
13324		     (if restrict-ok " (restricted to current file)" ""))
13325	    (setq c (read-char-exclusive)))
13326	  (message "")))
13327      (require 'calendar)  ; FIXME: can we avoid this for some commands?
13328      ;; For example the todo list should not need it (but does...)
13329      (cond
13330       ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
13331	(if (symbolp (nth 1 entry))
13332	    (progn
13333	      (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
13334		    lprops (nth 3 entry))
13335	      (cond
13336	       ((eq type 'tags)
13337		(org-let lprops '(org-tags-view current-prefix-arg match)))
13338	       ((eq type 'tags-todo)
13339		(org-let lprops '(org-tags-view '(4) match)))
13340	       ((eq type 'todo)
13341		(org-let lprops '(org-todo-list match)))
13342	       ((eq type 'tags-tree)
13343		(org-check-for-org-mode)
13344		(org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
13345	       ((eq type 'todo-tree)
13346		(org-check-for-org-mode)
13347		(org-let lprops
13348		  '(org-occur (concat "^" outline-regexp "[ \t]*"
13349				      (regexp-quote match) "\\>"))))
13350	       ((eq type 'occur-tree)
13351		(org-check-for-org-mode)
13352		(org-let lprops '(org-occur match)))
13353	       ((fboundp type)
13354		(org-let lprops '(funcall type match)))
13355	       (t (error "Invalid custom agenda command type %s" type))))
13356	  (org-run-agenda-series (cddr entry))))
13357       ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
13358       ((equal c ?a) (call-interactively 'org-agenda-list))
13359       ((equal c ?t) (call-interactively 'org-todo-list))
13360       ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
13361       ((equal c ?m) (call-interactively 'org-tags-view))
13362       ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
13363       ((equal c ?L)
13364	(unless restrict-ok
13365	  (error "This is not an Org-mode file"))
13366	(org-call-with-arg 'org-timeline arg))
13367       ((equal c ?#) (call-interactively 'org-agenda-list-stuck-projects))
13368       ((equal c ?!) (customize-variable 'org-stuck-projects))
13369       (t (error "Invalid key"))))))
13370
13371(defun org-run-agenda-series (series)
13372  (org-prepare-agenda)
13373  (let* ((org-agenda-multi t)
13374	 (redo (list 'org-run-agenda-series (list 'quote series)))
13375	 (cmds (car series))
13376	 (gprops (nth 1 series))
13377	 match ;; The byte compiler incorrectly complains about this.  Keep it!
13378	 cmd type lprops)
13379    (while (setq cmd (pop cmds))
13380      (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
13381      (cond
13382       ((eq type 'agenda)
13383	(call-interactively 'org-agenda-list))
13384       ((eq type 'alltodo)
13385	(call-interactively 'org-todo-list))
13386       ((eq type 'stuck)
13387	(call-interactively 'org-agenda-list-stuck-projects))
13388       ((eq type 'tags)
13389	(org-let2 gprops lprops
13390		  '(org-tags-view current-prefix-arg match)))
13391       ((eq type 'tags-todo)
13392	(org-let2 gprops lprops
13393		  '(org-tags-view '(4) match)))
13394       ((eq type 'todo)
13395	(org-let2 gprops lprops
13396		  '(org-todo-list match)))
13397       ((fboundp type)
13398	(org-let2 gprops lprops
13399	  '(funcall type match)))
13400       (t (error "Invalid type in command series"))))
13401    (widen)
13402    (setq org-agenda-redo-command redo)
13403    (goto-char (point-min)))
13404  (org-finalize-agenda))
13405
13406;;;###autoload
13407(defmacro org-batch-agenda (cmd-key &rest parameters)
13408  "Run an agenda command in batch mode, send result to STDOUT.
13409CMD-KEY is a string that is also a key in `org-agenda-custom-commands'.
13410Paramters are alternating variable names and values that will be bound
13411before running the agenda command."
13412  (let (pars)
13413    (while parameters
13414      (push (list (pop parameters) (if parameters (pop parameters))) pars))
13415    (flet ((read-char-exclusive () (string-to-char cmd-key)))
13416      (eval (list 'let (nreverse pars) '(org-agenda nil))))
13417    (set-buffer "*Org Agenda*")
13418    (princ (buffer-string))))
13419
13420(defmacro org-no-read-only (&rest body)
13421  "Inhibit read-only for BODY."
13422  `(let ((inhibit-read-only t)) ,@body))
13423
13424(defun org-check-for-org-mode ()
13425  "Make sure current buffer is in org-mode.  Error if not."
13426  (or (org-mode-p)
13427      (error "Cannot execute org-mode agenda command on buffer in %s."
13428	     major-mode)))
13429
13430(defun org-fit-agenda-window ()
13431  "Fit the window to the buffer size."
13432  (and (memq org-agenda-window-setup '(reorganize-frame))
13433       (fboundp 'fit-window-to-buffer)
13434       (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
13435                             (/ (frame-height) 2))))
13436
13437;;; Agenda file list
13438
13439(defun org-agenda-files (&optional unrestricted)
13440  "Get the list of agenda files.
13441Optional UNRESTRICTED means return the full list even if a restriction
13442is currently in place."
13443  (cond
13444   ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13445   ((stringp org-agenda-files) (org-read-agenda-file-list))
13446   ((listp org-agenda-files) org-agenda-files)
13447   (t (error "Invalid value of `org-agenda-files'"))))
13448
13449(defun org-edit-agenda-file-list ()
13450  "Edit the list of agenda files.
13451Depending on setup, this either uses customize to edit the variable
13452`org-agenda-files', or it visits the file that is holding the list.  In the
13453latter case, the buffer is set up in a way that saving it automatically kills
13454the buffer and restores the previous window configuration."
13455  (interactive)
13456  (if (stringp org-agenda-files)
13457      (let ((cw (current-window-configuration)))
13458	(find-file org-agenda-files)
13459	(org-set-local 'org-window-configuration cw)
13460	(org-add-hook 'after-save-hook
13461		      (lambda ()
13462			(set-window-configuration
13463			 (prog1 org-window-configuration
13464			   (kill-buffer (current-buffer))))
13465			(org-install-agenda-files-menu)
13466			(message "New agenda file list installed"))
13467		      nil 'local)
13468	(message (substitute-command-keys
13469		  "Edit list and finish with \\[save-buffer]")))
13470    (customize-variable 'org-agenda-files)))
13471
13472(defun org-store-new-agenda-file-list (list)
13473  "Set new value for the agenda file list and save it correcly."
13474  (if (stringp org-agenda-files)
13475      (let ((f org-agenda-files) b)
13476	(while (setq b (find-buffer-visiting f)) (kill-buffer b))
13477	(with-temp-file f
13478	  (insert (mapconcat 'identity list "\n") "\n")))
13479    (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13480      (setq org-agenda-files list)
13481      (customize-save-variable 'org-agenda-files org-agenda-files))))
13482
13483(defun org-read-agenda-file-list ()
13484  "Read the list of agenda files from a file."
13485  (when (stringp org-agenda-files)
13486    (with-temp-buffer
13487      (insert-file-contents org-agenda-files)
13488      (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13489
13490
13491;;;###autoload
13492(defun org-cycle-agenda-files ()
13493  "Cycle through the files in `org-agenda-files'.
13494If the current buffer visits an agenda file, find the next one in the list.
13495If the current buffer does not, find the first agenda file."
13496  (interactive)
13497  (let* ((fs (org-agenda-files t))
13498	 (files (append fs (list (car fs))))
13499	 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13500	 file)
13501    (unless files (error "No agenda files"))
13502    (catch 'exit
13503      (while (setq file (pop files))
13504	(if (equal (file-truename file) tcf)
13505	    (when (car files)
13506	      (find-file (car files))
13507	      (throw 'exit t))))
13508      (find-file (car fs)))
13509    (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13510
13511(defun org-agenda-file-to-end ()
13512  "Move/add the current file to the end of the agenda file list.
13513If the file is not present in the list, it is appended to the list.  If it is
13514present, it is moved there."
13515  (interactive)
13516  (org-agenda-file-to-front 'to-end))
13517
13518(defun org-agenda-file-to-front (&optional to-end)
13519  "Move/add the current file to the top of the agenda file list.
13520If the file is not present in the list, it is added to the front.  If it is
13521present, it is moved there.  With optional argument TO-END, add/move to the
13522end of the list."
13523  (interactive "P")
13524  (let ((file-alist (mapcar (lambda (x)
13525			      (cons (file-truename x) x))
13526			    (org-agenda-files t)))
13527	(ctf (file-truename buffer-file-name))
13528	x had)
13529    (setq x (assoc ctf file-alist) had x)
13530
13531    (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13532    (if to-end
13533	(setq file-alist (append (delq x file-alist) (list x)))
13534      (setq file-alist (cons x (delq x file-alist))))
13535    (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13536    (org-install-agenda-files-menu)
13537    (message "File %s to %s of agenda file list"
13538	     (if had "moved" "added") (if to-end "end" "front"))))
13539
13540(defun org-remove-file (&optional file)
13541  "Remove current file from the list of files in variable `org-agenda-files'.
13542These are the files which are being checked for agenda entries.
13543Optional argument FILE means, use this file instead of the current."
13544  (interactive)
13545  (let* ((file (or file buffer-file-name))
13546	 (true-file (file-truename file))
13547	 (afile (abbreviate-file-name file))
13548	 (files (delq nil (mapcar
13549			   (lambda (x)
13550			     (if (equal true-file
13551					(file-truename x))
13552				 nil x))
13553			   (org-agenda-files t)))))
13554    (if (not (= (length files) (length (org-agenda-files t))))
13555	(progn
13556	  (org-store-new-agenda-file-list files)
13557	  (org-install-agenda-files-menu)
13558	  (message "Removed file: %s" afile))
13559      (message "File was not in list: %s" afile))))
13560
13561(defun org-file-menu-entry (file)
13562  (vector file (list 'find-file file) t))
13563
13564(defun org-check-agenda-file (file)
13565  "Make sure FILE exists.  If not, ask user what to do."
13566  (when (not (file-exists-p file))
13567    (message "non-existent file %s. [R]emove from list or [A]bort?"
13568	     (abbreviate-file-name file))
13569    (let ((r (downcase (read-char-exclusive))))
13570      (cond
13571       ((equal r ?r)
13572	(org-remove-file file)
13573	(throw 'nextfile t))
13574       (t (error "Abort"))))))
13575
13576;;; Agenda prepare and finalize
13577
13578(defvar org-agenda-multi nil)  ; dynammically scoped
13579(defvar org-agenda-buffer-name "*Org Agenda*")
13580(defvar org-pre-agenda-window-conf nil)
13581(defun org-prepare-agenda ()
13582  (if org-agenda-multi
13583      (progn
13584	(setq buffer-read-only nil)
13585	(goto-char (point-max))
13586	(unless (= (point) 1)
13587	  (insert "\n" (make-string (window-width) ?=) "\n"))
13588	(narrow-to-region (point) (point-max)))
13589    (org-agenda-maybe-reset-markers 'force)
13590    (org-prepare-agenda-buffers (org-agenda-files))
13591    (let* ((abuf (get-buffer-create org-agenda-buffer-name))
13592	   (awin (get-buffer-window abuf)))
13593      (cond
13594       ((equal (current-buffer) abuf) nil)
13595       (awin (select-window awin))
13596       ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
13597       ((equal org-agenda-window-setup 'current-window)
13598	(switch-to-buffer abuf))
13599       ((equal org-agenda-window-setup 'other-window)
13600	(switch-to-buffer-other-window abuf))
13601       ((equal org-agenda-window-setup 'other-frame)
13602	(switch-to-buffer-other-frame abuf))
13603       ((equal org-agenda-window-setup 'reorganize-frame)
13604	(delete-other-windows)
13605	(switch-to-buffer-other-window abuf))))
13606    (setq buffer-read-only nil)
13607    (erase-buffer)
13608    (org-agenda-mode))
13609  (setq buffer-read-only nil))
13610
13611(defun org-finalize-agenda ()
13612  "Finishing touch for the agenda buffer, called just before displaying it."
13613  (unless org-agenda-multi
13614    (org-agenda-align-tags)
13615    (save-excursion
13616      (let ((buffer-read-only))
13617	(goto-char (point-min))
13618	(while (org-activate-bracket-links (point-max))
13619	  (add-text-properties (match-beginning 0) (match-end 0)
13620			       '(face org-link))))
13621      (run-hooks 'org-finalize-agenda-hook))))
13622
13623(defun org-prepare-agenda-buffers (files)
13624  "Create buffers for all agenda files, protect archived trees and comments."
13625  (interactive)
13626  (let ((pa '(:org-archived t))
13627	(pc '(:org-comment t))
13628	(pall '(:org-archived t :org-comment t))
13629	(rea (concat ":" org-archive-tag ":"))
13630	     bmp file re)
13631    (save-excursion
13632      (save-restriction
13633	(while (setq file (pop files))
13634	  (org-check-agenda-file file)
13635	  (set-buffer (org-get-agenda-file-buffer file))
13636	  (widen)
13637	  (setq bmp (buffer-modified-p))
13638	  (save-excursion
13639	    (remove-text-properties (point-min) (point-max) pall)
13640	    (when org-agenda-skip-archived-trees
13641	      (goto-char (point-min))
13642	      (while (re-search-forward rea nil t)
13643		(if (org-on-heading-p t)
13644		    (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13645	    (goto-char (point-min))
13646	    (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13647	    (while (re-search-forward re nil t)
13648	      (add-text-properties
13649	       (match-beginning 0) (org-end-of-subtree t) pc)))
13650	  (set-buffer-modified-p bmp))))))
13651
13652(defvar org-agenda-skip-function nil
13653  "Function to be called at each match during agenda construction.
13654If this function return nil, the current match should not be skipped.
13655Otherwise, the function must return a position from where the search
13656should be continued.
13657Never set this variable using `setq' or so, because then it will apply
13658to all future agenda commands.  Instead, bind it with `let' to scope
13659it dynamically into the agenda-constructing command.")
13660
13661(defun org-agenda-skip ()
13662  "Throw to `:skip' in places that should be skipped.
13663Also moves point to the end of the skipped region, so that search can
13664continue from there."
13665  (let ((p (point-at-bol)) to)
13666    (and org-agenda-skip-archived-trees
13667	 (get-text-property p :org-archived)
13668	 (org-end-of-subtree t)
13669	 (throw :skip t))
13670    (and (get-text-property p :org-comment)
13671	 (org-end-of-subtree t)
13672	 (throw :skip t))
13673    (if (equal (char-after p) ?#) (throw :skip t))
13674    (when (and (functionp org-agenda-skip-function)
13675	       (setq to (save-excursion
13676			  (save-match-data
13677			    (funcall org-agenda-skip-function)))))
13678      (goto-char to)
13679      (throw :skip t))))
13680
13681(defvar org-agenda-markers nil
13682  "List of all currently active markers created by `org-agenda'.")
13683(defvar org-agenda-last-marker-time (time-to-seconds (current-time))
13684  "Creation time of the last agenda marker.")
13685
13686(defun org-agenda-new-marker (&optional pos)
13687  "Return a new agenda marker.
13688Org-mode keeps a list of these markers and resets them when they are
13689no longer in use."
13690  (let ((m (copy-marker (or pos (point)))))
13691    (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
13692    (push m org-agenda-markers)
13693    m))
13694
13695(defun org-agenda-maybe-reset-markers (&optional force)
13696  "Reset markers created by `org-agenda'.  But only if they are old enough."
13697  (if (or (and force (not org-agenda-multi))
13698	  (> (- (time-to-seconds (current-time))
13699		org-agenda-last-marker-time)
13700	     5))
13701      (while org-agenda-markers
13702	(move-marker (pop org-agenda-markers) nil))))
13703
13704(defvar org-agenda-new-buffers nil
13705  "Buffers created to visit agenda files.")
13706
13707(defun org-get-agenda-file-buffer (file)
13708  "Get a buffer visiting FILE.  If the buffer needs to be created, add
13709it to the list of buffers which might be released later."
13710  (let ((buf (org-find-base-buffer-visiting file)))
13711    (if buf
13712	buf ; just return it
13713      ;; Make a new buffer and remember it
13714      (setq buf (find-file-noselect file))
13715      (if buf (push buf org-agenda-new-buffers))
13716      buf)))
13717
13718(defun org-release-buffers (blist)
13719  "Release all buffers in list, asking the user for confirmation when needed.
13720When a buffer is unmodified, it is just killed.  When modified, it is saved
13721\(if the user agrees) and then killed."
13722  (let (buf file)
13723    (while (setq buf (pop blist))
13724      (setq file (buffer-file-name buf))
13725      (when (and (buffer-modified-p buf)
13726		 file
13727		 (y-or-n-p (format "Save file %s? " file)))
13728	(with-current-buffer buf (save-buffer)))
13729      (kill-buffer buf))))
13730
13731(defvar org-category-table nil)
13732(defun org-get-category-table ()
13733  "Get the table of categories and positions in current buffer."
13734  (let (tbl)
13735    (save-excursion
13736      (goto-char (point-min))
13737      (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
13738	(push (cons (point) (org-trim (match-string 2))) tbl)))
13739    tbl))
13740
13741(defun org-get-category (&optional pos)
13742  "Get the category applying to position POS."
13743  (if (not org-category-table)
13744      (cond
13745       ((null org-category)
13746	(setq org-category
13747	      (if buffer-file-name
13748		  (file-name-sans-extension
13749		   (file-name-nondirectory buffer-file-name))
13750		"???")))
13751       ((symbolp org-category) (symbol-name org-category))
13752       (t org-category))
13753    (let ((tbl org-category-table)
13754	  (pos (or pos (point))))
13755      (while (and tbl (> (caar tbl) pos))
13756	(pop tbl))
13757      (or (cdar tbl) (cdr (nth (1- (length org-category-table))
13758			       org-category-table))))))
13759;;; Agenda timeline
13760
13761(defun org-timeline (&optional include-all)
13762  "Show a time-sorted view of the entries in the current org file.
13763Only entries with a time stamp of today or later will be listed.  With
13764\\[universal-argument] prefix, all unfinished TODO items will also be shown,
13765under the current date.
13766If the buffer contains an active region, only check the region for
13767dates."
13768  (interactive "P")
13769  (require 'calendar)
13770  (org-compile-prefix-format 'timeline)
13771  (org-set-sorting-strategy 'timeline)
13772  (let* ((dopast t)
13773	 (dotodo include-all)
13774	 (doclosed org-agenda-show-log)
13775	 (entry buffer-file-name)
13776	 (date (calendar-current-date))
13777	 (beg (if (org-region-active-p) (region-beginning) (point-min)))
13778	 (end (if (org-region-active-p) (region-end) (point-max)))
13779	 (day-numbers (org-get-all-dates beg end 'no-ranges
13780					 t doclosed ; always include today
13781					 org-timeline-show-empty-dates))
13782	 (today (time-to-days (current-time)))
13783	 (past t)
13784	 args
13785	 s e rtn d emptyp)
13786    (setq org-agenda-redo-command
13787	  (list 'progn
13788		(list 'switch-to-buffer-other-window (current-buffer))
13789		(list 'org-timeline (list 'quote include-all))))
13790    (if (not dopast)
13791	;; Remove past dates from the list of dates.
13792	(setq day-numbers (delq nil (mapcar (lambda(x)
13793					      (if (>= x today) x nil))
13794					    day-numbers))))
13795    (org-prepare-agenda)
13796    (if doclosed (push :closed args))
13797    (push :timestamp args)
13798    (if dotodo (push :todo args))
13799    (while (setq d (pop day-numbers))
13800      (if (and (listp d) (eq (car d) :omitted))
13801	  (progn
13802	    (setq s (point))
13803	    (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
13804	    (put-text-property s (1- (point)) 'face 'org-level-3))
13805	(if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
13806	(if (and (>= d today)
13807		 dopast
13808		 past)
13809	    (progn
13810	      (setq past nil)
13811	      (insert (make-string 79 ?-) "\n")))
13812	(setq date (calendar-gregorian-from-absolute d))
13813	(setq s (point))
13814	(setq rtn (and (not emptyp)
13815		       (apply 'org-agenda-get-day-entries
13816			      entry date args)))
13817	(if (or rtn (equal d today) org-timeline-show-empty-dates)
13818	    (progn
13819	      (insert (calendar-day-name date) " "
13820		      (number-to-string (extract-calendar-day date)) " "
13821		      (calendar-month-name (extract-calendar-month date)) " "
13822		      (number-to-string (extract-calendar-year date)) "\n")
13823; FIXME: this gives a timezone problem
13824;	      (insert (format-time-string org-agenda-date-format
13825;					  (calendar-time-from-absolute d 0))
13826;		      "\n")
13827	      (put-text-property s (1- (point)) 'face 'org-level-3)
13828	      (put-text-property s (1- (point)) 'org-date-line t)
13829	      (if (equal d today)
13830		  (put-text-property s (1- (point)) 'org-today t))
13831	      (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
13832	      (put-text-property s (1- (point)) 'day d)))))
13833    (goto-char (point-min))
13834    (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
13835		   (point-min)))
13836    (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
13837    (org-finalize-agenda)
13838    (setq buffer-read-only t)))
13839
13840(defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
13841  "Return a list of all relevant day numbers from BEG to END buffer positions.
13842If NO-RANGES is non-nil, include only the start and end dates of a range,
13843not every single day in the range.  If FORCE-TODAY is non-nil, make
13844sure that TODAY is included in the list.  If INACTIVE is non-nil, also
13845inactive time stamps (those in square brackets) are included.
13846When EMPTY is non-nil, also include days without any entries."
13847  (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
13848	 dates dates1 date day day1 day2 ts1 ts2)
13849    (if force-today
13850	(setq dates (list (time-to-days (current-time)))))
13851    (save-excursion
13852      (goto-char beg)
13853      (while (re-search-forward re end t)
13854	(setq day (time-to-days (org-time-string-to-time
13855				 (substring (match-string 1) 0 10))))
13856	(or (memq day dates) (push day dates)))
13857      (unless no-ranges
13858	(goto-char beg)
13859	(while (re-search-forward org-tr-regexp end t)
13860	  (setq ts1 (substring (match-string 1) 0 10)
13861		ts2 (substring (match-string 2) 0 10)
13862		day1 (time-to-days (org-time-string-to-time ts1))
13863		day2 (time-to-days (org-time-string-to-time ts2)))
13864	  (while (< (setq day1 (1+ day1)) day2)
13865	    (or (memq day1 dates) (push day1 dates)))))
13866      (setq dates (sort dates '<))
13867      (when empty
13868	(while (setq day (pop dates))
13869	  (setq day2 (car dates))
13870	  (push day dates1)
13871	  (when (and day2 empty)
13872	    (if (or (eq empty t)
13873		    (and (numberp empty) (<= (- day2 day) empty)))
13874		(while (< (setq day (1+ day)) day2)
13875		  (push (list day) dates1))
13876	      (push (cons :omitted (- day2 day)) dates1))))
13877	(setq dates (nreverse dates1)))
13878      dates)))
13879
13880;;; Agenda Daily/Weekly
13881
13882(defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
13883(defvar org-agenda-last-arguments nil
13884  "The arguments of the previous call to org-agenda")
13885(defvar org-starting-day nil) ; local variable in the agenda buffer
13886(defvar org-include-all-loc nil) ; local variable
13887
13888
13889;;;###autoload
13890(defun org-agenda-list (&optional include-all start-day ndays)
13891  "Produce a weekly view from all files in variable `org-agenda-files'.
13892The view will be for the current week, but from the overview buffer you
13893will be able to go to other weeks.
13894With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
13895also be shown, under the current date.
13896With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
13897on the days are also shown.  See the variable `org-log-done' for how
13898to turn on logging.
13899START-DAY defaults to TODAY, or to the most recent match for the weekday
13900given in `org-agenda-start-on-weekday'.
13901NDAYS defaults to `org-agenda-ndays'."
13902  (interactive "P")
13903  (if org-agenda-overriding-arguments
13904      (setq include-all (car org-agenda-overriding-arguments)
13905	    start-day (nth 1 org-agenda-overriding-arguments)
13906	    ndays (nth 2 org-agenda-overriding-arguments)))
13907  (setq org-agenda-last-arguments (list include-all start-day ndays))
13908  (org-compile-prefix-format 'agenda)
13909  (org-set-sorting-strategy 'agenda)
13910  (require 'calendar)
13911  (let* ((org-agenda-start-on-weekday
13912	  (if (or (equal ndays 1)
13913		  (and (null ndays) (equal 1 org-agenda-ndays)))
13914	      nil org-agenda-start-on-weekday))
13915	 (thefiles (org-agenda-files))
13916	 (files thefiles)
13917	 (today (time-to-days (current-time)))
13918	 (sd (or start-day today))
13919	 (start (if (or (null org-agenda-start-on-weekday)
13920			(< org-agenda-ndays 7))
13921		    sd
13922		  (let* ((nt (calendar-day-of-week
13923			      (calendar-gregorian-from-absolute sd)))
13924			 (n1 org-agenda-start-on-weekday)
13925			 (d (- nt n1)))
13926		    (- sd (+ (if (< d 0) 7 0) d)))))
13927	 (day-numbers (list start))
13928	 (inhibit-redisplay (not debug-on-error))
13929	 s e rtn rtnall file date d start-pos end-pos todayp nd)
13930    (setq org-agenda-redo-command
13931	  (list 'org-agenda-list (list 'quote include-all) start-day ndays))
13932    ;; Make the list of days
13933    (setq ndays (or ndays org-agenda-ndays)
13934	  nd ndays)
13935    (while (> ndays 1)
13936      (push (1+ (car day-numbers)) day-numbers)
13937      (setq ndays (1- ndays)))
13938    (setq day-numbers (nreverse day-numbers))
13939    (org-prepare-agenda)
13940    (org-set-local 'org-starting-day (car day-numbers))
13941    (org-set-local 'org-include-all-loc include-all)
13942    (when (and (or include-all org-agenda-include-all-todo)
13943	       (member today day-numbers))
13944      (setq files thefiles
13945	    rtnall nil)
13946      (while (setq file (pop files))
13947	(catch 'nextfile
13948	  (org-check-agenda-file file)
13949	  (setq date (calendar-gregorian-from-absolute today)
13950		rtn (org-agenda-get-day-entries
13951		     file date :todo))
13952	  (setq rtnall (append rtnall rtn))))
13953      (when rtnall
13954	(insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
13955	(add-text-properties (point-min) (1- (point))
13956			     (list 'face 'org-level-3))
13957	(insert (org-finalize-agenda-entries rtnall) "\n")))
13958    (setq s (point))
13959    (insert (if (= nd 7) "Week-" "Day-") "agenda:\n")
13960    (add-text-properties s (1- (point)) (list 'face 'org-level-3))
13961    (while (setq d (pop day-numbers))
13962      (setq date (calendar-gregorian-from-absolute d)
13963	    s (point))
13964      (if (or (setq todayp (= d today))
13965	      (and (not start-pos) (= d sd)))
13966	  (setq start-pos (point))
13967	(if (and start-pos (not end-pos))
13968	    (setq end-pos (point))))
13969      (setq files thefiles
13970	    rtnall nil)
13971      (while (setq file (pop files))
13972	(catch 'nextfile
13973	  (org-check-agenda-file file)
13974	  (if org-agenda-show-log
13975	      (setq rtn (org-agenda-get-day-entries
13976			 file date
13977			 :deadline :scheduled :timestamp :closed))
13978	    (setq rtn (org-agenda-get-day-entries
13979		       file date
13980		       :deadline :scheduled :timestamp)))
13981	  (setq rtnall (append rtnall rtn))))
13982      (if org-agenda-include-diary
13983	  (progn
13984	    (require 'diary-lib)
13985	    (setq rtn (org-get-entries-from-diary date))
13986	    (setq rtnall (append rtnall rtn))))
13987      (if (or rtnall org-agenda-show-all-dates)
13988	  (progn
13989	    (insert (format "%-9s %2d %s %4d\n"
13990			    (calendar-day-name date)
13991			    (extract-calendar-day date)
13992			    (calendar-month-name (extract-calendar-month date))
13993			    (extract-calendar-year date)))
13994; FIXME: this gives a timezone problem
13995;	    (insert (format-time-string org-agenda-date-format
13996;					(calendar-time-from-absolute d 0)) "\n")
13997	    (put-text-property s (1- (point)) 'face 'org-level-3)
13998	    (put-text-property s (1- (point)) 'org-date-line t)
13999	    (if todayp (put-text-property s (1- (point)) 'org-today t))
14000	    (if rtnall (insert
14001			(org-finalize-agenda-entries
14002			 (org-agenda-add-time-grid-maybe
14003			  rtnall nd todayp))
14004			"\n"))
14005	    (put-text-property s (1- (point)) 'day d))))
14006    (goto-char (point-min))
14007    (org-fit-agenda-window)
14008    (unless (and (pos-visible-in-window-p (point-min))
14009		 (pos-visible-in-window-p (point-max)))
14010      (goto-char (1- (point-max)))
14011      (recenter -1)
14012      (if (not (pos-visible-in-window-p (or start-pos 1)))
14013	  (progn
14014	    (goto-char (or start-pos 1))
14015	    (recenter 1))))
14016    (goto-char (or start-pos 1))
14017    (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
14018    (org-finalize-agenda)
14019    (setq buffer-read-only t)
14020    (message "")))
14021
14022;;; Agenda TODO list
14023
14024(defvar org-select-this-todo-keyword nil)
14025(defvar org-last-arg nil)
14026
14027;;;###autoload
14028(defun org-todo-list (arg)
14029  "Show all TODO entries from all agenda file in a single list.
14030The prefix arg can be used to select a specific TODO keyword and limit
14031the list to these.  When using \\[universal-argument], you will be prompted
14032for a keyword.  A numeric prefix directly selects the Nth keyword in
14033`org-todo-keywords'."
14034  (interactive "P")
14035  (require 'calendar)
14036  (org-compile-prefix-format 'todo)
14037  (org-set-sorting-strategy 'todo)
14038  (let* ((today (time-to-days (current-time)))
14039	 (date (calendar-gregorian-from-absolute today))
14040	 (kwds org-todo-keywords)
14041	 (completion-ignore-case t)
14042	 (org-select-this-todo-keyword
14043	  (if (stringp arg) arg
14044	    (and arg (integerp arg) (> arg 0)
14045                 (nth (1- arg) org-todo-keywords))))
14046	 rtn rtnall files file pos)
14047    (when (equal arg '(4))
14048      (setq org-select-this-todo-keyword
14049	    (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
14050			     nil t)))
14051    (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
14052    (org-prepare-agenda)
14053    (org-set-local 'org-last-arg arg)
14054    (org-set-local 'org-todo-keywords kwds)
14055    (setq org-agenda-redo-command
14056	  '(org-todo-list (or current-prefix-arg org-last-arg)))
14057    (setq files (org-agenda-files)
14058	  rtnall nil)
14059    (while (setq file (pop files))
14060      (catch 'nextfile
14061	(org-check-agenda-file file)
14062	(setq rtn (org-agenda-get-day-entries file date :todo))
14063	(setq rtnall (append rtnall rtn))))
14064    (if org-agenda-overriding-header
14065	(insert (org-add-props (copy-sequence org-agenda-overriding-header)
14066		    nil 'face 'org-level-3) "\n")
14067      (insert "Global list of TODO items of type: ")
14068      (add-text-properties (point-min) (1- (point))
14069			   (list 'face 'org-level-3))
14070      (setq pos (point))
14071      (insert (or org-select-this-todo-keyword "ALL") "\n")
14072      (add-text-properties pos (1- (point)) (list 'face 'org-warning))
14073      (setq pos (point))
14074      (unless org-agenda-multi
14075	(insert
14076	 "Available with `N r': (0)ALL "
14077	 (let ((n 0))
14078	   (mapconcat (lambda (x)
14079			(format "(%d)%s" (setq n (1+ n)) x))
14080		      org-todo-keywords " "))
14081	 "\n"))
14082      (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
14083    (when rtnall
14084      (insert (org-finalize-agenda-entries rtnall) "\n"))
14085    (goto-char (point-min))
14086    (org-fit-agenda-window)
14087    (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
14088    (org-finalize-agenda)
14089    (setq buffer-read-only t)))
14090
14091;;; Agenda tags match
14092
14093;;;###autoload
14094(defun org-tags-view (&optional todo-only match)
14095  "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
14096The prefix arg TODO-ONLY limits the search to TODO entries."
14097  (interactive "P")
14098  (org-compile-prefix-format 'tags)
14099  (org-set-sorting-strategy 'tags)
14100  (let* ((org-tags-match-list-sublevels
14101	  (if todo-only t org-tags-match-list-sublevels))
14102	 (completion-ignore-case t)
14103	 rtn rtnall files file pos matcher
14104	 buffer)
14105    (setq matcher (org-make-tags-matcher match)
14106	  match (car matcher) matcher (cdr matcher))
14107    (org-prepare-agenda)
14108    (setq org-agenda-redo-command
14109	  (list 'org-tags-view (list 'quote todo-only)
14110		(list 'if 'current-prefix-arg nil match)))
14111    (setq files (org-agenda-files)
14112	  rtnall nil)
14113    (while (setq file (pop files))
14114      (catch 'nextfile
14115	(org-check-agenda-file file)
14116	(setq buffer (if (file-exists-p file)
14117			 (org-get-agenda-file-buffer file)
14118		       (error "No such file %s" file)))
14119	(if (not buffer)
14120	    ;; If file does not exist, merror message to agenda
14121	    (setq rtn (list
14122		       (format "ORG-AGENDA-ERROR: No such org-file %s" file))
14123		  rtnall (append rtnall rtn))
14124	  (with-current-buffer buffer
14125	    (unless (org-mode-p)
14126	      (error "Agenda file %s is not in `org-mode'" file))
14127	    (setq org-category-table (org-get-category-table))
14128	    (save-excursion
14129	      (save-restriction
14130		(if org-agenda-restrict
14131		    (narrow-to-region org-agenda-restrict-begin
14132				      org-agenda-restrict-end)
14133		  (widen))
14134		(setq rtn (org-scan-tags 'agenda matcher todo-only))
14135		(setq rtnall (append rtnall rtn))))))))
14136    (if org-agenda-overriding-header
14137	(insert (org-add-props (copy-sequence org-agenda-overriding-header)
14138		    nil 'face 'org-level-3) "\n")
14139      (insert "Headlines with TAGS match: ")
14140      (add-text-properties (point-min) (1- (point))
14141			   (list 'face 'org-level-3))
14142      (setq pos (point))
14143      (insert match "\n")
14144      (add-text-properties pos (1- (point)) (list 'face 'org-warning))
14145      (setq pos (point))
14146      (unless org-agenda-multi
14147	(insert "Press `C-u r' to search again with new search string\n"))
14148      (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
14149    (when rtnall
14150      (insert (org-finalize-agenda-entries rtnall) "\n"))
14151    (goto-char (point-min))
14152    (org-fit-agenda-window)
14153    (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
14154    (org-finalize-agenda)
14155    (setq buffer-read-only t)))
14156
14157;;; Agenda Finding stuck projects
14158
14159(defvar org-agenda-skip-regexp nil
14160  "Regular expression used in skipping subtrees for the agenda.
14161This is basically a temporary global variable that can be set and then
14162used by user-defined selections using `org-agenda-skip-function'.")
14163
14164(defvar org-agenda-overriding-header nil
14165  "When this is set during todo and tags searches, will replace header.")
14166
14167(defun org-agenda-skip-subtree-when-regexp-matches ()
14168  "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
14169If yes, it returns the end position of this tree, causing agenda commands
14170to skip this subtree.  This is a function that can be put into
14171`org-agenda-skip-function' for the duration of a command."
14172  (save-match-data
14173    (let ((end (save-excursion (org-end-of-subtree t)))
14174	  skip)
14175      (save-excursion
14176	(setq skip (re-search-forward org-agenda-skip-regexp end t)))
14177      (and skip end))))
14178
14179(defun org-agenda-list-stuck-projects (&rest ignore)
14180  "Create agenda view for projects that are stuck.
14181Stuck projects are project that have no next actions.  For the definitions
14182of what a project is and how to check if it stuck, customize the variable
14183`org-stuck-projects'.
14184MATCH is being ignored."
14185  (interactive)
14186  (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
14187	 (org-agenda-overriding-header "List of stuck projects: ")
14188	 (matcher (nth 0 org-stuck-projects))
14189	 (todo (nth 1 org-stuck-projects))
14190	 (tags (nth 2 org-stuck-projects))
14191	 (todo-re (concat "^\\*+[ \t]+\\("
14192			  (mapconcat 'identity todo "\\|")
14193			  "\\)\\>"))
14194	 (tags-re (concat "^\\*+.*:\\("
14195			  (mapconcat 'identity tags "\\|")
14196			  "\\):[a-zA-Z0-9_@:]*[ \t]*$")))
14197
14198    (setq org-agenda-skip-regexp
14199	  (cond
14200	   ((and todo tags)
14201	    (concat todo-re "\\|" tags-re))
14202	   (todo todo-re)
14203	   (tags tags-re)
14204	   (t (error "No information how to identify unstuck projects"))))
14205    (org-tags-view nil matcher)
14206    (with-current-buffer org-agenda-buffer-name
14207      (setq org-agenda-redo-command
14208	    '(org-agenda-list-stuck-projects
14209	      (or current-prefix-arg org-last-arg))))))
14210
14211;;; Diary integration
14212
14213(defvar org-disable-agenda-to-diary nil)          ;Dynamically-scoped param.
14214
14215(defun org-get-entries-from-diary (date)
14216  "Get the (Emacs Calendar) diary entries for DATE."
14217  (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
14218	 (diary-display-hook '(fancy-diary-display))
14219	 (list-diary-entries-hook
14220	  (cons 'org-diary-default-entry list-diary-entries-hook))
14221	 (diary-file-name-prefix-function nil) ; turn this feature off
14222	 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
14223	 entries
14224	 (org-disable-agenda-to-diary t))
14225    (save-excursion
14226      (save-window-excursion
14227	(list-diary-entries date 1)))  ;; Keep this name for now, compatibility
14228    (if (not (get-buffer fancy-diary-buffer))
14229	(setq entries nil)
14230      (with-current-buffer fancy-diary-buffer
14231	(setq buffer-read-only nil)
14232	(if (= (point-max) 1)
14233	    ;; No entries
14234	    (setq entries nil)
14235	  ;; Omit the date and other unnecessary stuff
14236	  (org-agenda-cleanup-fancy-diary)
14237	  ;; Add prefix to each line and extend the text properties
14238	  (if (= (point-max) 1)
14239	      (setq entries nil)
14240	    (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
14241	(set-buffer-modified-p nil)
14242	(kill-buffer fancy-diary-buffer)))
14243    (when entries
14244      (setq entries (org-split-string entries "\n"))
14245      (setq entries
14246	    (mapcar
14247	     (lambda (x)
14248	       (setq x (org-format-agenda-item "" x "Diary" nil 'time))
14249	       ;; Extend the text properties to the beginning of the line
14250	       (org-add-props x (text-properties-at (1- (length x)) x)))
14251	     entries)))))
14252
14253(defun org-agenda-cleanup-fancy-diary ()
14254  "Remove unwanted stuff in buffer created by `fancy-diary-display'.
14255This gets rid of the date, the underline under the date, and
14256the dummy entry installed by `org-mode' to ensure non-empty diary for each
14257date.  It also removes lines that contain only whitespace."
14258  (goto-char (point-min))
14259  (if (looking-at ".*?:[ \t]*")
14260      (progn
14261	(replace-match "")
14262	(re-search-forward "\n=+$" nil t)
14263	(replace-match "")
14264	(while (re-search-backward "^ +\n?" nil t) (replace-match "")))
14265    (re-search-forward "\n=+$" nil t)
14266    (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
14267  (goto-char (point-min))
14268  (while (re-search-forward "^ +\n" nil t)
14269    (replace-match ""))
14270  (goto-char (point-min))
14271  (if (re-search-forward "^Org-mode dummy\n?" nil t)
14272      (replace-match "")))
14273
14274;; Make sure entries from the diary have the right text properties.
14275(eval-after-load "diary-lib"
14276  '(if (boundp 'diary-modify-entry-list-string-function)
14277       ;; We can rely on the hook, nothing to do
14278       nil
14279     ;; Hook not avaiable, must use advice to make this work
14280     (defadvice add-to-diary-list (before org-mark-diary-entry activate)
14281       "Make the position visible."
14282       (if (and org-disable-agenda-to-diary  ;; called from org-agenda
14283		(stringp string)
14284		buffer-file-name)
14285	   (setq string (org-modify-diary-entry-string string))))))
14286
14287(defun org-modify-diary-entry-string (string)
14288  "Add text properties to string, allowing org-mode to act on it."
14289  (org-add-props string nil
14290    'mouse-face 'highlight
14291    'keymap org-agenda-keymap
14292    'help-echo (format "mouse-2 or RET jump to diary file %s"
14293		       (abbreviate-file-name buffer-file-name))
14294    'org-agenda-diary-link t
14295    'org-marker (org-agenda-new-marker (point-at-bol))))
14296
14297(defun org-diary-default-entry ()
14298  "Add a dummy entry to the diary.
14299Needed to avoid empty dates which mess up holiday display."
14300  ;; Catch the error if dealing with the new add-to-diary-alist
14301  (when org-disable-agenda-to-diary
14302    (condition-case nil
14303	(add-to-diary-list original-date "Org-mode dummy" "")
14304      (error
14305       (add-to-diary-list original-date  "Org-mode dummy" "" nil)))))
14306
14307;;;###autoload
14308(defun org-diary (&rest args)
14309  "Return diary information from org-files.
14310This function can be used in a \"sexp\" diary entry in the Emacs calendar.
14311It accesses org files and extracts information from those files to be
14312listed in the diary.  The function accepts arguments specifying what
14313items should be listed.  The following arguments are allowed:
14314
14315   :timestamp    List the headlines of items containing a date stamp or
14316		 date range matching the selected date.  Deadlines will
14317		 also be listed, on the expiration day.
14318
14319   :deadline     List any deadlines past due, or due within
14320		 `org-deadline-warning-days'.  The listing occurs only
14321		 in the diary for *today*, not at any other date.  If
14322		 an entry is marked DONE, it is no longer listed.
14323
14324   :scheduled    List all items which are scheduled for the given date.
14325		 The diary for *today* also contains items which were
14326		 scheduled earlier and are not yet marked DONE.
14327
14328   :todo         List all TODO items from the org-file.  This may be a
14329		 long list - so this is not turned on by default.
14330		 Like deadlines, these entries only show up in the
14331		 diary for *today*, not at any other date.
14332
14333The call in the diary file should look like this:
14334
14335   &%%(org-diary) ~/path/to/some/orgfile.org
14336
14337Use a separate line for each org file to check.  Or, if you omit the file name,
14338all files listed in `org-agenda-files' will be checked automatically:
14339
14340   &%%(org-diary)
14341
14342If you don't give any arguments (as in the example above), the default
14343arguments (:deadline :scheduled :timestamp) are used.  So the example above may
14344also be written as
14345
14346   &%%(org-diary :deadline :timestamp :scheduled)
14347
14348The function expects the lisp variables `entry' and `date' to be provided
14349by the caller, because this is how the calendar works.  Don't use this
14350function from a program - use `org-agenda-get-day-entries' instead."
14351  (org-agenda-maybe-reset-markers)
14352  (org-compile-prefix-format 'agenda)
14353  (org-set-sorting-strategy 'agenda)
14354  (setq args (or args '(:deadline :scheduled :timestamp)))
14355  (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
14356		    (list entry)
14357		  (org-agenda-files t)))
14358	 file rtn results)
14359    ;; If this is called during org-agenda, don't return any entries to
14360    ;; the calendar.  Org Agenda will list these entries itself.
14361    (if org-disable-agenda-to-diary (setq files nil))
14362    (while (setq file (pop files))
14363      (setq rtn (apply 'org-agenda-get-day-entries file date args))
14364      (setq results (append results rtn)))
14365    (if results
14366	(concat (org-finalize-agenda-entries results) "\n"))))
14367
14368;;; Agenda entry finders
14369
14370(defun org-agenda-get-day-entries (file date &rest args)
14371  "Does the work for `org-diary' and `org-agenda'.
14372FILE is the path to a file to be checked for entries.  DATE is date like
14373the one returned by `calendar-current-date'.  ARGS are symbols indicating
14374which kind of entries should be extracted.  For details about these, see
14375the documentation of `org-diary'."
14376  (setq args (or args '(:deadline :scheduled :timestamp)))
14377  (let* ((org-startup-folded nil)
14378	 (org-startup-align-all-tables nil)
14379	 (buffer (if (file-exists-p file)
14380		     (org-get-agenda-file-buffer file)
14381		   (error "No such file %s" file)))
14382	 arg results rtn)
14383    (if (not buffer)
14384	;; If file does not exist, make sure an error message ends up in diary
14385	(list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
14386      (with-current-buffer buffer
14387	(unless (org-mode-p)
14388	  (error "Agenda file %s is not in `org-mode'" file))
14389	(setq org-category-table (org-get-category-table))
14390	(let ((case-fold-search nil))
14391	  (save-excursion
14392	    (save-restriction
14393	      (if org-agenda-restrict
14394		  (narrow-to-region org-agenda-restrict-begin
14395				    org-agenda-restrict-end)
14396		(widen))
14397	      ;; The way we repeatedly append to `results' makes it O(n^2) :-(
14398	      (while (setq arg (pop args))
14399		(cond
14400		 ((and (eq arg :todo)
14401		       (equal date (calendar-current-date)))
14402		  (setq rtn (org-agenda-get-todos))
14403		  (setq results (append results rtn)))
14404		 ((eq arg :timestamp)
14405		  (setq rtn (org-agenda-get-blocks))
14406		  (setq results (append results rtn))
14407		  (setq rtn (org-agenda-get-timestamps))
14408		  (setq results (append results rtn)))
14409		 ((eq arg :scheduled)
14410		  (setq rtn (org-agenda-get-scheduled))
14411		  (setq results (append results rtn)))
14412		 ((eq arg :closed)
14413		  (setq rtn (org-agenda-get-closed))
14414		  (setq results (append results rtn)))
14415		 ((and (eq arg :deadline)
14416		       (equal date (calendar-current-date)))
14417		  (setq rtn (org-agenda-get-deadlines))
14418		  (setq results (append results rtn))))))))
14419	results))))
14420
14421(defun org-entry-is-done-p ()
14422  "Is the current entry marked DONE?"
14423  (save-excursion
14424    (and (re-search-backward "[\r\n]\\*" nil t)
14425	 (looking-at org-nl-done-regexp))))
14426
14427(defun org-at-date-range-p (&optional inactive-ok)
14428  "Is the cursor inside a date range?"
14429  (interactive)
14430  (save-excursion
14431    (catch 'exit
14432      (let ((pos (point)))
14433	(skip-chars-backward "^[<\r\n")
14434	(skip-chars-backward "<[")
14435	(and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
14436	     (>= (match-end 0) pos)
14437	     (throw 'exit t))
14438	(skip-chars-backward "^<[\r\n")
14439	(skip-chars-backward "<[")
14440	(and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
14441	     (>= (match-end 0) pos)
14442	     (throw 'exit t)))
14443      nil)))
14444
14445(defun org-agenda-get-todos ()
14446  "Return the TODO information for agenda display."
14447  (let* ((props (list 'face nil
14448		      'done-face 'org-done
14449		      'org-not-done-regexp org-not-done-regexp
14450		      'mouse-face 'highlight
14451		      'keymap org-agenda-keymap
14452		      'help-echo
14453		      (format "mouse-2 or RET jump to org file %s"
14454			      (abbreviate-file-name buffer-file-name))))
14455	 (regexp (concat "[\n\r]\\*+ *\\("
14456			 (if org-select-this-todo-keyword
14457			     (concat "\\<\\(" org-select-this-todo-keyword
14458				     "\\)\\>")
14459			   org-not-done-regexp)
14460			 "[^\n\r]*\\)"))
14461	 marker priority category tags
14462	 ee txt beg end)
14463    (goto-char (point-min))
14464    (while (re-search-forward regexp nil t)
14465      (catch :skip
14466	(save-match-data
14467	  (beginning-of-line)
14468	  (setq beg (point) end (progn (outline-next-heading) (point)))
14469	  (when (or (and org-agenda-todo-ignore-scheduled (goto-char beg)
14470			 (re-search-forward org-scheduled-time-regexp end t))
14471		    (and org-agenda-todo-ignore-deadlines (goto-char beg)
14472			 (re-search-forward org-deadline-time-regexp end t)
14473			 (org-deadline-close (match-string 1))))
14474	    (goto-char beg)
14475	    (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
14476	    (throw :skip nil)))
14477	(goto-char beg)
14478	(org-agenda-skip)
14479	(goto-char (match-beginning 1))
14480	(setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
14481	      category (org-get-category)
14482	      tags (org-get-tags-at (point))
14483	      txt (org-format-agenda-item "" (match-string 1) category tags)
14484	      priority
14485	      (+ (org-get-priority txt)
14486		 (if org-todo-kwd-priority-p
14487		     (- org-todo-kwd-max-priority -2
14488			(length
14489			 (member (match-string 2) org-todo-keywords)))
14490		     1)))
14491	(org-add-props txt props
14492	  'org-marker marker 'org-hd-marker marker
14493	  'priority priority 'org-category category)
14494	(push txt ee)
14495	(if org-agenda-todo-list-sublevels
14496	    (goto-char (match-end 1))
14497	  (org-end-of-subtree 'invisible))))
14498    (nreverse ee)))
14499
14500(defconst org-agenda-no-heading-message
14501  "No heading for this item in buffer or region.")
14502
14503(defun org-agenda-get-timestamps ()
14504  "Return the date stamp information for agenda display."
14505  (let* ((props (list 'face nil
14506		      'org-not-done-regexp org-not-done-regexp
14507		      'mouse-face 'highlight
14508		      'keymap org-agenda-keymap
14509		      'help-echo
14510		      (format "mouse-2 or RET jump to org file %s"
14511			      (abbreviate-file-name buffer-file-name))))
14512	 (regexp (regexp-quote
14513		  (substring
14514		   (format-time-string
14515		    (car org-time-stamp-formats)
14516		    (apply 'encode-time  ; DATE bound by calendar
14517			   (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
14518		   0 11)))
14519	 marker hdmarker deadlinep scheduledp donep tmp priority category
14520	 ee txt timestr tags)
14521    (goto-char (point-min))
14522    (while (re-search-forward regexp nil t)
14523      (catch :skip
14524	(and (save-match-data (org-at-date-range-p)) (throw :skip nil))
14525	(org-agenda-skip)
14526	(setq marker (org-agenda-new-marker (match-beginning 0))
14527	      category (org-get-category (match-beginning 0))
14528	      tmp (buffer-substring (max (point-min)
14529					 (- (match-beginning 0)
14530					    org-ds-keyword-length))
14531				    (match-beginning 0))
14532	      timestr (buffer-substring (match-beginning 0) (point-at-eol))
14533	      deadlinep (string-match org-deadline-regexp tmp)
14534	      scheduledp (string-match org-scheduled-regexp tmp)
14535	      donep (org-entry-is-done-p))
14536	(and org-agenda-skip-scheduled-if-done
14537	     scheduledp donep
14538	     (throw :skip t))
14539	(if (string-match ">" timestr)
14540	    ;; substring should only run to end of time stamp
14541	    (setq timestr (substring timestr 0 (match-end 0))))
14542	(save-excursion
14543	  (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
14544	      (progn
14545		(goto-char (match-end 1))
14546		(setq hdmarker (org-agenda-new-marker)
14547		      tags (org-get-tags-at))
14548		(looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
14549		(setq txt (org-format-agenda-item
14550			   (format "%s%s"
14551				   (if deadlinep  "Deadline:  " "")
14552				   (if scheduledp "Scheduled: " ""))
14553			   (match-string 1) category tags timestr)))
14554	    (setq txt org-agenda-no-heading-message))
14555	  (setq priority (org-get-priority txt))
14556	  (org-add-props txt props
14557	    'org-marker marker 'org-hd-marker hdmarker)
14558	  (if deadlinep
14559	      (org-add-props txt nil
14560		'face (if donep 'org-done 'org-warning)
14561		'undone-face 'org-warning 'done-face 'org-done
14562		'org-category category 'priority (+ 100 priority))
14563	    (if scheduledp
14564		(org-add-props txt nil
14565		  'face 'org-scheduled-today
14566		  'undone-face 'org-scheduled-today 'done-face 'org-done
14567		  'org-category category 'priority (+ 99 priority))
14568	      (org-add-props txt nil 'priority priority 'org-category category)))
14569	  (push txt ee))
14570	(outline-next-heading)))
14571    (nreverse ee)))
14572
14573(defun org-agenda-get-closed ()
14574  "Return the logged TODO entries for agenda display."
14575  (let* ((props (list 'mouse-face 'highlight
14576		      'org-not-done-regexp org-not-done-regexp
14577		      'keymap org-agenda-keymap
14578		      'help-echo
14579		      (format "mouse-2 or RET jump to org file %s"
14580			      (abbreviate-file-name buffer-file-name))))
14581	 (regexp (concat
14582		  "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
14583		  (regexp-quote
14584		   (substring
14585		    (format-time-string
14586		     (car org-time-stamp-formats)
14587		     (apply 'encode-time  ; DATE bound by calendar
14588			    (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
14589		    1 11))))
14590	 marker hdmarker priority category tags closedp
14591	 ee txt timestr)
14592    (goto-char (point-min))
14593    (while (re-search-forward regexp nil t)
14594      (catch :skip
14595	(org-agenda-skip)
14596	(setq marker (org-agenda-new-marker (match-beginning 0))
14597	      closedp (equal (match-string 1) org-closed-string)
14598	      category (org-get-category (match-beginning 0))
14599	      timestr (buffer-substring (match-beginning 0) (point-at-eol))
14600	      ;; donep (org-entry-is-done-p)
14601	      )
14602	(if (string-match "\\]" timestr)
14603	    ;; substring should only run to end of time stamp
14604	    (setq timestr (substring timestr 0 (match-end 0))))
14605	(save-excursion
14606	  (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
14607	      (progn
14608		(goto-char (match-end 1))
14609		(setq hdmarker (org-agenda-new-marker)
14610		      tags (org-get-tags-at))
14611		(looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
14612		(setq txt (org-format-agenda-item
14613			   (if closedp "Closed:    " "Clocked:   ")
14614			   (match-string 1) category tags timestr)))
14615	    (setq txt org-agenda-no-heading-message))
14616	  (setq priority 100000)
14617	  (org-add-props txt props
14618	    'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
14619	    'priority priority 'org-category category
14620	    'undone-face 'org-warning 'done-face 'org-done)
14621	  (push txt ee))
14622	(outline-next-heading)))
14623    (nreverse ee)))
14624
14625(defun org-agenda-get-deadlines ()
14626  "Return the deadline information for agenda display."
14627  (let* ((wdays org-deadline-warning-days)
14628	 (props (list 'mouse-face 'highlight
14629		      'org-not-done-regexp org-not-done-regexp
14630		      'keymap org-agenda-keymap
14631		      'help-echo
14632		      (format "mouse-2 or RET jump to org file %s"
14633			      (abbreviate-file-name buffer-file-name))))
14634	 (regexp org-deadline-time-regexp)
14635	 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
14636	 (d1 (calendar-absolute-from-gregorian date))  ; DATE bound by calendar
14637	 d2 diff pos pos1 category tags
14638	 ee txt head face)
14639    (goto-char (point-min))
14640    (while (re-search-forward regexp nil t)
14641      (catch :skip
14642	(org-agenda-skip)
14643	(setq pos (1- (match-beginning 1))
14644	      d2 (time-to-days
14645		  (org-time-string-to-time (match-string 1)))
14646	      diff (- d2 d1))
14647	;; When to show a deadline in the calendar:
14648	;; If the expiration is within wdays warning time.
14649	;; Past-due deadlines are only shown on the current date
14650	(if (and (< diff wdays) todayp (not (= diff 0)))
14651	    (save-excursion
14652	      (setq category (org-get-category))
14653	      (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
14654		  (progn
14655		    (goto-char (match-end 0))
14656		    (setq pos1 (match-end 1))
14657		    (setq tags (org-get-tags-at pos1))
14658		    (setq head (buffer-substring-no-properties
14659				(point)
14660				(progn (skip-chars-forward "^\r\n")
14661				       (point))))
14662		    (if (string-match org-looking-at-done-regexp head)
14663			(setq txt nil)
14664		      (setq txt (org-format-agenda-item
14665				 (format "In %3d d.: " diff) head category tags))))
14666		(setq txt org-agenda-no-heading-message))
14667	      (when txt
14668		(setq face (cond ((<= diff 0) 'org-warning)
14669				 ((<= diff 5) 'org-upcoming-deadline)
14670				 (t nil)))
14671		(org-add-props txt props
14672		  'org-marker (org-agenda-new-marker pos)
14673		  'org-hd-marker (org-agenda-new-marker pos1)
14674		  'priority (+ (- 10 diff) (org-get-priority txt))
14675		  'org-category category
14676		  'face face 'undone-face face 'done-face 'org-done)
14677		(push txt ee))))))
14678    ee))
14679
14680(defun org-agenda-get-scheduled ()
14681  "Return the scheduled information for agenda display."
14682  (let* ((props (list 'face 'org-scheduled-previously
14683		      'org-not-done-regexp org-not-done-regexp
14684		      'undone-face 'org-scheduled-previously
14685		      'done-face 'org-done
14686		      'mouse-face 'highlight
14687		      'keymap org-agenda-keymap
14688		      'help-echo
14689		      (format "mouse-2 or RET jump to org file %s"
14690			      (abbreviate-file-name buffer-file-name))))
14691	 (regexp org-scheduled-time-regexp)
14692	 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
14693	 (d1 (calendar-absolute-from-gregorian date))  ; DATE bound by calendar
14694	 d2 diff pos pos1 category tags
14695	 ee txt head)
14696    (goto-char (point-min))
14697    (while (re-search-forward regexp nil t)
14698      (catch :skip
14699	(org-agenda-skip)
14700	(setq pos (1- (match-beginning 1))
14701	      d2 (time-to-days
14702		  (org-time-string-to-time (match-string 1)))
14703	      diff (- d2 d1))
14704	;; When to show a scheduled item in the calendar:
14705	;; If it is on or past the date.
14706	(if (and (< diff 0) todayp)
14707	    (save-excursion
14708	      (setq category (org-get-category))
14709	      (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
14710		  (progn
14711		    (goto-char (match-end 0))
14712		    (setq pos1 (match-end 1))
14713		    (setq tags (org-get-tags-at))
14714		    (setq head (buffer-substring-no-properties
14715				(point)
14716				(progn (skip-chars-forward "^\r\n") (point))))
14717		    (if (string-match org-looking-at-done-regexp head)
14718			(setq txt nil)
14719		      (setq txt (org-format-agenda-item
14720				 (format "Sched.%2dx: " (- 1 diff)) head
14721				 category tags))))
14722		(setq txt org-agenda-no-heading-message))
14723	      (when txt
14724		(org-add-props txt props
14725		  'org-marker (org-agenda-new-marker pos)
14726		  'org-hd-marker (org-agenda-new-marker pos1)
14727		  'priority (+ (- 5 diff) (org-get-priority txt))
14728		  'org-category category)
14729		(push txt ee))))))
14730    ee))
14731
14732(defun org-agenda-get-blocks ()
14733  "Return the date-range information for agenda display."
14734  (let* ((props (list 'face nil
14735		      'org-not-done-regexp org-not-done-regexp
14736		      'mouse-face 'highlight
14737		      'keymap org-agenda-keymap
14738		      'help-echo
14739		      (format "mouse-2 or RET jump to org file %s"
14740			      (abbreviate-file-name buffer-file-name))))
14741	 (regexp org-tr-regexp)
14742	 (d0 (calendar-absolute-from-gregorian date))
14743	 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
14744    (goto-char (point-min))
14745    (while (re-search-forward regexp nil t)
14746      (catch :skip
14747	(org-agenda-skip)
14748	(setq pos (point))
14749	(setq timestr (match-string 0)
14750	      s1 (match-string 1)
14751	      s2 (match-string 2)
14752	      d1 (time-to-days (org-time-string-to-time s1))
14753	      d2 (time-to-days (org-time-string-to-time s2)))
14754	(if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
14755	    ;; Only allow days between the limits, because the normal
14756	    ;; date stamps will catch the limits.
14757	    (save-excursion
14758	      (setq marker (org-agenda-new-marker (point)))
14759	      (setq category (org-get-category))
14760	      (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
14761		  (progn
14762		    (setq hdmarker (org-agenda-new-marker (match-end 1)))
14763		    (goto-char (match-end 1))
14764		    (setq tags (org-get-tags-at))
14765		    (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
14766		    (setq txt (org-format-agenda-item
14767			       (format (if (= d1 d2) "" "(%d/%d): ")
14768				       (1+ (- d0 d1)) (1+ (- d2 d1)))
14769			       (match-string 1) category tags
14770			       (if (= d0 d1) timestr))))
14771		(setq txt org-agenda-no-heading-message))
14772	      (org-add-props txt props
14773		'org-marker marker 'org-hd-marker hdmarker
14774		'priority (org-get-priority txt) 'org-category category)
14775	      (push txt ee)))
14776	(goto-char pos)))
14777    ;; Sort the entries by expiration date.
14778    (nreverse ee)))
14779
14780;;; Agenda presentation and sorting
14781
14782;; FIXME: should I allow spaces around the dash?
14783(defconst org-plain-time-of-day-regexp
14784  (concat
14785   "\\(\\<[012]?[0-9]"
14786   "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
14787   "\\(--?"
14788   "\\(\\<[012]?[0-9]"
14789   "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
14790   "\\)?")
14791  "Regular expression to match a plain time or time range.
14792Examples:  11:45 or 8am-13:15 or 2:45-2:45pm.  After a match, the following
14793groups carry important information:
147940  the full match
147951  the first time, range or not
147968  the second time, if it is a range.")
14797
14798(defconst org-stamp-time-of-day-regexp
14799  (concat
14800   "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
14801   "\\([012][0-9]:[0-5][0-9]\\)>"
14802   "\\(--?"
14803   "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
14804  "Regular expression to match a timestamp time or time range.
14805After a match, the following groups carry important information:
148060  the full match
148071  date plus weekday, for backreferencing to make sure both times on same day
148082  the first time, range or not
148094  the second time, if it is a range.")
14810
14811(defvar org-prefix-has-time nil
14812  "A flag, set by `org-compile-prefix-format'.
14813The flag is set if the currently compiled format contains a `%t'.")
14814(defvar org-prefix-has-tag nil
14815  "A flag, set by `org-compile-prefix-format'.
14816The flag is set if the currently compiled format contains a `%T'.")
14817
14818(defun org-format-agenda-item (extra txt &optional category tags dotime
14819				     noprefix)
14820  "Format TXT to be inserted into the agenda buffer.
14821In particular, it adds the prefix and corresponding text properties.  EXTRA
14822must be a string and replaces the `%s' specifier in the prefix format.
14823CATEGORY (string, symbol or nil) may be used to overrule the default
14824category taken from local variable or file name.  It will replace the `%c'
14825specifier in the format.  DOTIME, when non-nil, indicates that a
14826time-of-day should be extracted from TXT for sorting of this entry, and for
14827the `%t' specifier in the format.  When DOTIME is a string, this string is
14828searched for a time before TXT is.  NOPREFIX is a flag and indicates that
14829only the correctly processes TXT should be returned - this is used by
14830`org-agenda-change-all-lines'.  TAGS can be the tags of the headline."
14831  (save-match-data
14832    ;; Diary entries sometimes have extra whitespace at the beginning
14833    (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
14834    (let* ((category (or category
14835			 org-category
14836			 (if buffer-file-name
14837			     (file-name-sans-extension
14838			      (file-name-nondirectory buffer-file-name))
14839			   "")))
14840	   (tag (if tags (nth (1- (length tags)) tags) ""))
14841	   time    ; time and tag are needed for the eval of the prefix format
14842	   (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
14843	   (time-of-day (and dotime (org-get-time-of-day ts)))
14844	   stamp plain s0 s1 s2 rtn)
14845      (when (and dotime time-of-day org-prefix-has-time)
14846	;; Extract starting and ending time and move them to prefix
14847	(when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
14848		  (setq plain (string-match org-plain-time-of-day-regexp ts)))
14849	  (setq s0 (match-string 0 ts)
14850		s1 (match-string (if plain 1 2) ts)
14851		s2 (match-string (if plain 8 4) ts))
14852
14853	  ;; If the times are in TXT (not in DOTIMES), and the prefix will list
14854	  ;; them, we might want to remove them there to avoid duplication.
14855	  ;; The user can turn this off with a variable.
14856	  (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
14857		   (string-match (concat (regexp-quote s0) " *") txt)
14858		   (if (eq org-agenda-remove-times-when-in-prefix 'beg)
14859		       (= (match-beginning 0) 0)
14860		     t))
14861	      (setq txt (replace-match "" nil nil txt))))
14862	;; Normalize the time(s) to 24 hour
14863	(if s1 (setq s1 (org-get-time-of-day s1 'string t)))
14864	(if s2 (setq s2 (org-get-time-of-day s2 'string t))))
14865
14866      (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
14867	;; Tags are in the string
14868	(if (or (eq org-agenda-remove-tags-when-in-prefix t)
14869		(and org-agenda-remove-tags-when-in-prefix
14870		     org-prefix-has-tag))
14871	    (setq txt (replace-match "" t t txt))
14872	  (setq txt (replace-match
14873		     (concat (make-string (max (- 50 (length txt)) 1) ?\ )
14874			     (match-string 2 txt))
14875		     t t txt))))
14876
14877      ;; Create the final string
14878      (if noprefix
14879	  (setq rtn txt)
14880	;; Prepare the variables needed in the eval of the compiled format
14881	(setq time (cond (s2 (concat s1 "-" s2))
14882			 (s1 (concat s1 "......"))
14883			 (t ""))
14884	      extra (or extra "")
14885	      category (if (symbolp category) (symbol-name category) category))
14886	;; Evaluate the compiled format
14887	(setq rtn (concat (eval org-prefix-format-compiled) txt)))
14888
14889      ;; And finally add the text properties
14890      (org-add-props rtn nil
14891	'org-category (downcase category) 'tags tags
14892	'prefix-length (- (length rtn) (length txt))
14893	'time-of-day time-of-day
14894	'dotime dotime))))
14895
14896(defvar org-agenda-sorting-strategy)
14897(defvar org-agenda-sorting-strategy-selected nil)
14898
14899(defun org-agenda-add-time-grid-maybe (list ndays todayp)
14900  (catch 'exit
14901    (cond ((not org-agenda-use-time-grid) (throw 'exit list))
14902	  ((and todayp (member 'today (car org-agenda-time-grid))))
14903	  ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
14904	  ((member 'weekly (car org-agenda-time-grid)))
14905	  (t (throw 'exit list)))
14906    (let* ((have (delq nil (mapcar
14907			    (lambda (x) (get-text-property 1 'time-of-day x))
14908			    list)))
14909	   (string (nth 1 org-agenda-time-grid))
14910	   (gridtimes (nth 2 org-agenda-time-grid))
14911	   (req (car org-agenda-time-grid))
14912	   (remove (member 'remove-match req))
14913	   new time)
14914      (if (and (member 'require-timed req) (not have))
14915	  ;; don't show empty grid
14916	  (throw 'exit list))
14917      (while (setq time (pop gridtimes))
14918	(unless (and remove (member time have))
14919	  (setq time (int-to-string time))
14920	  (push (org-format-agenda-item
14921		 nil string "" nil
14922		 (concat (substring time 0 -2) ":" (substring time -2)))
14923		new)
14924	  (put-text-property
14925	   1 (length (car new)) 'face 'org-time-grid (car new))))
14926      (if (member 'time-up org-agenda-sorting-strategy-selected)
14927	  (append new list)
14928	(append list new)))))
14929
14930(defun org-compile-prefix-format (key)
14931  "Compile the prefix format into a Lisp form that can be evaluated.
14932The resulting form is returned and stored in the variable
14933`org-prefix-format-compiled'."
14934  (setq org-prefix-has-time nil org-prefix-has-tag nil)
14935  (let ((s (cond
14936	    ((stringp org-agenda-prefix-format)
14937	     org-agenda-prefix-format)
14938	    ((assq key org-agenda-prefix-format)
14939	     (cdr (assq key org-agenda-prefix-format)))
14940	    (t "  %-12:c%?-12t% s")))
14941	(start 0)
14942	varform vars var e c f opt)
14943    (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
14944			 s start)
14945      (setq var (cdr (assoc (match-string 4 s)
14946			    '(("c" . category) ("t" . time) ("s" . extra)
14947			      ("T" . tag))))
14948	    c (or (match-string 3 s) "")
14949	    opt (match-beginning 1)
14950	    start (1+ (match-beginning 0)))
14951      (if (equal var 'time) (setq org-prefix-has-time t))
14952      (if (equal var 'tag)  (setq org-prefix-has-tag  t))
14953      (setq f (concat "%" (match-string 2 s) "s"))
14954      (if opt
14955	  (setq varform
14956		`(if (equal "" ,var)
14957		     ""
14958		   (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
14959	(setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
14960      (setq s (replace-match "%s" t nil s))
14961      (push varform vars))
14962    (setq vars (nreverse vars))
14963    (setq org-prefix-format-compiled `(format ,s ,@vars))))
14964
14965(defun org-set-sorting-strategy (key)
14966  (if (symbolp (car org-agenda-sorting-strategy))
14967      ;; the old format
14968      (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
14969    (setq org-agenda-sorting-strategy-selected
14970	  (or (cdr (assq key org-agenda-sorting-strategy))
14971	      (cdr (assq 'agenda org-agenda-sorting-strategy))
14972	      '(time-up category-keep priority-down)))))
14973
14974(defun org-get-time-of-day (s &optional string mod24)
14975  "Check string S for a time of day.
14976If found, return it as a military time number between 0 and 2400.
14977If not found, return nil.
14978The optional STRING argument forces conversion into a 5 character wide string
14979HH:MM."
14980  (save-match-data
14981    (when
14982     (or
14983      (string-match
14984       "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
14985      (string-match
14986       "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
14987     (let* ((h (string-to-number (match-string 1 s)))
14988	    (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
14989	    (ampm (if (match-end 4) (downcase (match-string 4 s))))
14990	    (am-p (equal ampm "am"))
14991	    (h1   (cond ((not ampm) h)
14992			((= h 12) (if am-p 0 12))
14993			(t (+ h (if am-p 0 12)))))
14994	    (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
14995		    (mod h1 24) h1))
14996	    (t0 (+ (* 100 h2) m))
14997	    (t1 (concat (if (>= h1 24) "+" " ")
14998			(if (< t0 100) "0" "")
14999			(if (< t0 10)  "0" "")
15000			(int-to-string t0))))
15001       (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
15002
15003(defun org-finalize-agenda-entries (list &optional nosort)
15004  "Sort and concatenate the agenda items."
15005  (setq list (mapcar 'org-agenda-highlight-todo list))
15006  (if nosort
15007      list
15008    (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
15009
15010(defun org-agenda-highlight-todo (x)
15011  (let (re pl)
15012    (if (eq x 'line)
15013	(save-excursion
15014	  (beginning-of-line 1)
15015	  (setq re (get-text-property (point) 'org-not-done-regexp))
15016	  (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
15017	  (and (looking-at (concat "[ \t]*\\.*" re))
15018	       (add-text-properties (match-beginning 0) (match-end 0)
15019				    '(face org-todo))))
15020      (setq re (concat (get-text-property 0 'org-not-done-regexp x))
15021	    pl (get-text-property 0 'prefix-length x))
15022      (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
15023	   (add-text-properties (or (match-end 1) (match-end 0)) (match-end 0)
15024				'(face org-todo) x))
15025      x)))
15026
15027(defsubst org-cmp-priority (a b)
15028  "Compare the priorities of string A and B."
15029  (let ((pa (or (get-text-property 1 'priority a) 0))
15030	(pb (or (get-text-property 1 'priority b) 0)))
15031    (cond ((> pa pb) +1)
15032	  ((< pa pb) -1)
15033	  (t nil))))
15034
15035(defsubst org-cmp-category (a b)
15036  "Compare the string values of categories of strings A and B."
15037  (let ((ca (or (get-text-property 1 'category a) ""))
15038	(cb (or (get-text-property 1 'category b) "")))
15039    (cond ((string-lessp ca cb) -1)
15040	  ((string-lessp cb ca) +1)
15041	  (t nil))))
15042
15043(defsubst org-cmp-tag (a b)
15044  "Compare the string values of categories of strings A and B."
15045  (let ((ta (car (last (get-text-property 1 'tags a))))
15046	(tb (car (last (get-text-property 1 'tags b)))))
15047    (cond ((not ta) +1)
15048	  ((not tb) -1)
15049	  ((string-lessp ta tb) -1)
15050	  ((string-lessp tb ta) +1)
15051	  (t nil))))
15052
15053(defsubst org-cmp-time (a b)
15054  "Compare the time-of-day values of strings A and B."
15055  (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
15056	 (ta (or (get-text-property 1 'time-of-day a) def))
15057	 (tb (or (get-text-property 1 'time-of-day b) def)))
15058    (cond ((< ta tb) -1)
15059	  ((< tb ta) +1)
15060	  (t nil))))
15061
15062(defun org-entries-lessp (a b)
15063  "Predicate for sorting agenda entries."
15064  ;; The following variables will be used when the form is evaluated.
15065  ;; So even though the compiler complains, keep them.
15066  (let* ((time-up (org-cmp-time a b))
15067	 (time-down (if time-up (- time-up) nil))
15068	 (priority-up (org-cmp-priority a b))
15069	 (priority-down (if priority-up (- priority-up) nil))
15070	 (category-up (org-cmp-category a b))
15071	 (category-down (if category-up (- category-up) nil))
15072	 (category-keep (if category-up +1 nil))
15073	 (tag-up (org-cmp-tag a b))
15074	 (tag-down (if tag-up (- tag-up) nil)))
15075    (cdr (assoc
15076	  (eval (cons 'or org-agenda-sorting-strategy-selected))
15077	  '((-1 . t) (1 . nil) (nil . nil))))))
15078
15079;;; Agenda commands
15080
15081(defun org-agenda-check-type (error &rest types)
15082  "Check if agenda buffer is of allowed type.
15083If ERROR is non-nil, throw an error, otherwise just return nil."
15084  (if (memq org-agenda-type types)
15085      t
15086    (if error
15087	(error "Not allowed in %s-type agenda buffers" org-agenda-type)
15088      nil)))
15089
15090(defun org-agenda-quit ()
15091  "Exit agenda by removing the window or the buffer."
15092  (interactive)
15093  (let ((buf (current-buffer)))
15094    (if (not (one-window-p)) (delete-window))
15095    (kill-buffer buf)
15096    (org-agenda-maybe-reset-markers 'force))
15097  ;; Maybe restore the pre-agenda window configuration.
15098  (and org-agenda-restore-windows-after-quit
15099       (not (eq org-agenda-window-setup 'other-frame))
15100       org-pre-agenda-window-conf
15101       (set-window-configuration org-pre-agenda-window-conf)))
15102
15103(defun org-agenda-exit ()
15104  "Exit agenda by removing the window or the buffer.
15105Also kill all Org-mode buffers which have been loaded by `org-agenda'.
15106Org-mode buffers visited directly by the user will not be touched."
15107  (interactive)
15108  (org-release-buffers org-agenda-new-buffers)
15109  (setq org-agenda-new-buffers nil)
15110  (org-agenda-quit))
15111
15112(defun org-save-all-org-buffers ()
15113  "Save all Org-mode buffers without user confirmation."
15114  (interactive)
15115  (message "Saving all Org-mode buffers...")
15116  (save-some-buffers t 'org-mode-p)
15117  (message "Saving all Org-mode buffers... done"))
15118
15119(defun org-agenda-redo ()
15120  "Rebuild Agenda.
15121When this is the global TODO list, a prefix argument will be interpreted."
15122  (interactive)
15123  (let* ((org-agenda-keep-modes t)
15124	 (line (org-current-line))
15125	 (window-line (- line (org-current-line (window-start)))))
15126    (message "Rebuilding agenda buffer...")
15127    (eval org-agenda-redo-command)
15128    (setq org-agenda-undo-list nil
15129	  org-agenda-pending-undo-list nil)
15130    (message "Rebuilding agenda buffer...done")
15131    (goto-line line)
15132    (recenter window-line)))
15133
15134(defun org-agenda-goto-today ()
15135  "Go to today."
15136  (interactive)
15137  (org-agenda-check-type t 'timeline 'agenda)
15138  (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
15139    (cond
15140     (tdpos (goto-char tdpos))
15141     ((eq org-agenda-type 'agenda)
15142      (let ((org-agenda-overriding-arguments org-agenda-last-arguments))
15143	(setf (nth 1 org-agenda-overriding-arguments) nil)
15144	(org-agenda-redo)
15145	(org-agenda-find-today-or-agenda)))
15146     (t (error "Cannot find today")))))
15147
15148(defun org-agenda-find-today-or-agenda ()
15149  (goto-char
15150   (or (text-property-any (point-min) (point-max) 'org-today t)
15151       (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
15152       (point-min))))
15153
15154(defun org-agenda-later (arg)
15155  "Go forward in time by `org-agenda-ndays' days.
15156With prefix ARG, go forward that many times `org-agenda-ndays'."
15157  (interactive "p")
15158  (org-agenda-check-type t 'agenda)
15159  (let ((org-agenda-overriding-arguments
15160	 (list (car org-agenda-last-arguments)
15161	       (+ org-starting-day (* arg org-agenda-ndays))
15162	       nil t)))
15163    (org-agenda-redo)
15164    (org-agenda-find-today-or-agenda)))
15165
15166(defun org-agenda-earlier (arg)
15167  "Go back in time by `org-agenda-ndays' days.
15168With prefix ARG, go back that many times `org-agenda-ndays'."
15169  (interactive "p")
15170  (org-agenda-check-type t 'agenda)
15171  (let ((org-agenda-overriding-arguments
15172	 (list (car org-agenda-last-arguments)
15173	       (- org-starting-day (* arg org-agenda-ndays))
15174	       nil t)))
15175    (org-agenda-redo)
15176    (org-agenda-find-today-or-agenda)))
15177
15178(defun org-agenda-week-view ()
15179  "Switch to weekly view for agenda."
15180  (interactive)
15181  (org-agenda-check-type t 'agenda)
15182  (if (= org-agenda-ndays 7)
15183      (error "This is already the week view"))
15184  (setq org-agenda-ndays 7)
15185  (let ((org-agenda-overriding-arguments
15186	 (list (car org-agenda-last-arguments)
15187	       (or (get-text-property (point) 'day)
15188		       org-starting-day)
15189	       nil t)))
15190    (org-agenda-redo)
15191    (org-agenda-find-today-or-agenda))
15192  (org-agenda-set-mode-name)
15193  (message "Switched to week view"))
15194
15195(defun org-agenda-day-view ()
15196  "Switch to daily view for agenda."
15197  (interactive)
15198  (org-agenda-check-type t 'agenda)
15199  (if (= org-agenda-ndays 1)
15200      (error "This is already the day view"))
15201  (setq org-agenda-ndays 1)
15202  (let ((org-agenda-overriding-arguments
15203	 (list (car org-agenda-last-arguments)
15204	       (or (get-text-property (point) 'day)
15205		       org-starting-day)
15206	       nil t)))
15207    (org-agenda-redo)
15208    (org-agenda-find-today-or-agenda))
15209  (org-agenda-set-mode-name)
15210  (message "Switched to day view"))
15211
15212;; FIXME: this no longer works if user make date format that starts with a blank
15213(defun org-agenda-next-date-line (&optional arg)
15214  "Jump to the next line indicating a date in agenda buffer."
15215  (interactive "p")
15216  (org-agenda-check-type t 'agenda 'timeline)
15217  (beginning-of-line 1)
15218  (if (looking-at "^\\S-") (forward-char 1))
15219  (if (not (re-search-forward "^\\S-" nil t arg))
15220      (progn
15221	(backward-char 1)
15222	(error "No next date after this line in this buffer")))
15223  (goto-char (match-beginning 0)))
15224
15225(defun org-agenda-previous-date-line (&optional arg)
15226  "Jump to the previous line indicating a date in agenda buffer."
15227  (interactive "p")
15228  (org-agenda-check-type t 'agenda 'timeline)
15229  (beginning-of-line 1)
15230  (if (not (re-search-backward "^\\S-" nil t arg))
15231      (error "No previous date before this line in this buffer")))
15232
15233;; Initialize the highlight
15234(defvar org-hl (org-make-overlay 1 1))
15235(org-overlay-put org-hl 'face 'highlight)
15236
15237(defun org-highlight (begin end &optional buffer)
15238  "Highlight a region with overlay."
15239  (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
15240	   org-hl begin end (or buffer (current-buffer))))
15241
15242(defun org-unhighlight ()
15243  "Detach overlay INDEX."
15244  (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
15245
15246(defun org-highlight-until-next-command (beg end &optional buffer)
15247  (org-highlight beg end buffer)
15248  (add-hook 'pre-command-hook 'org-unhighlight-once))
15249
15250(defun org-unhighlight-once ()
15251  (remove-hook 'pre-command-hook 'org-unhighlight-once)
15252  (org-unhighlight))
15253
15254(defun org-agenda-follow-mode ()
15255  "Toggle follow mode in an agenda buffer."
15256  (interactive)
15257  (setq org-agenda-follow-mode (not org-agenda-follow-mode))
15258  (org-agenda-set-mode-name)
15259  (message "Follow mode is %s"
15260	   (if org-agenda-follow-mode "on" "off")))
15261
15262(defun org-agenda-log-mode ()
15263  "Toggle log mode in an agenda buffer."
15264  (interactive)
15265  (org-agenda-check-type t 'agenda 'timeline)
15266  (setq org-agenda-show-log (not org-agenda-show-log))
15267  (org-agenda-set-mode-name)
15268  (org-agenda-redo)
15269  (message "Log mode is %s"
15270	   (if org-agenda-show-log "on" "off")))
15271
15272(defun org-agenda-toggle-diary ()
15273  "Toggle diary inclusion in an agenda buffer."
15274  (interactive)
15275  (org-agenda-check-type t 'agenda)
15276  (setq org-agenda-include-diary (not org-agenda-include-diary))
15277  (org-agenda-redo)
15278  (org-agenda-set-mode-name)
15279  (message "Diary inclusion turned %s"
15280	   (if org-agenda-include-diary "on" "off")))
15281
15282(defun org-agenda-toggle-time-grid ()
15283  "Toggle time grid in an agenda buffer."
15284  (interactive)
15285  (org-agenda-check-type t 'agenda)
15286  (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
15287  (org-agenda-redo)
15288  (org-agenda-set-mode-name)
15289  (message "Time-grid turned %s"
15290	   (if org-agenda-use-time-grid "on" "off")))
15291
15292(defun org-agenda-set-mode-name ()
15293  "Set the mode name to indicate all the small mode settings."
15294  (setq mode-name
15295	(concat "Org-Agenda"
15296		(if (equal org-agenda-ndays 1) " Day"    "")
15297		(if (equal org-agenda-ndays 7) " Week"   "")
15298		(if org-agenda-follow-mode     " Follow" "")
15299		(if org-agenda-include-diary   " Diary"  "")
15300		(if org-agenda-use-time-grid   " Grid"   "")
15301		(if org-agenda-show-log        " Log"    "")))
15302  (force-mode-line-update))
15303
15304(defun org-agenda-post-command-hook ()
15305  (and (eolp) (not (bolp)) (backward-char 1))
15306  (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
15307  (if (and org-agenda-follow-mode
15308	   (get-text-property (point) 'org-marker))
15309      (org-agenda-show)))
15310
15311(defun org-agenda-show-priority ()
15312  "Show the priority of the current item.
15313This priority is composed of the main priority given with the [#A] cookies,
15314and by additional input from the age of a schedules or deadline entry."
15315  (interactive)
15316  (let* ((pri (get-text-property (point-at-bol) 'priority)))
15317    (message "Priority is %d" (if pri pri -1000))))
15318
15319(defun org-agenda-show-tags ()
15320  "Show the tags applicable to the current item."
15321  (interactive)
15322  (let* ((tags (get-text-property (point-at-bol) 'tags)))
15323    (if tags
15324	(message "Tags are :%s:"
15325		 (org-no-properties (mapconcat 'identity tags ":")))
15326      (message "No tags associated with this line"))))
15327
15328(defun org-agenda-goto (&optional highlight)
15329  "Go to the Org-mode file which contains the item at point."
15330  (interactive)
15331  (let* ((marker (or (get-text-property (point) 'org-marker)
15332		     (org-agenda-error)))
15333	 (buffer (marker-buffer marker))
15334	 (pos (marker-position marker)))
15335    (switch-to-buffer-other-window buffer)
15336    (widen)
15337    (goto-char pos)
15338    (when (org-mode-p)
15339      (org-show-context 'agenda)
15340      (save-excursion
15341	(and (outline-next-heading)
15342	     (org-flag-heading nil)))) ; show the next heading
15343    (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
15344
15345(defun org-agenda-kill ()
15346  "Kill the entry or subtree belonging to the current agenda entry."
15347  (interactive)
15348  (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
15349  (let* ((marker (or (get-text-property (point) 'org-marker)
15350		     (org-agenda-error)))
15351	 (buffer (marker-buffer marker))
15352	 (pos (marker-position marker))
15353	 dbeg dend (n 0) conf)
15354    (org-with-remote-undo buffer
15355     (with-current-buffer buffer
15356       (save-excursion
15357	 (goto-char pos)
15358	 (if (org-mode-p)
15359	     (setq dbeg (progn (org-back-to-heading t) (point))
15360		   dend (org-end-of-subtree t))
15361	   (setq dbeg (point-at-bol)
15362		 dend (min (point-max) (1+ (point-at-eol)))))
15363	 (goto-char dbeg)
15364	 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
15365     (setq conf (or (eq t org-agenda-confirm-kill)
15366		    (and (numberp org-agenda-confirm-kill)
15367			 (> n org-agenda-confirm-kill))))
15368     (and conf
15369	  (not (y-or-n-p
15370		(format "Delete entry with %d lines in buffer \"%s\"? "
15371			n (buffer-name buffer))))
15372	  (error "Abort"))
15373     (org-remove-subtree-entries-from-agenda buffer dbeg dend)
15374     (with-current-buffer buffer (delete-region dbeg dend))
15375     (message "Agenda item and source killed"))))
15376
15377(defun org-agenda-archive ()
15378  "Kill the entry or subtree belonging to the current agenda entry."
15379  (interactive)
15380  (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
15381  (let* ((marker (or (get-text-property (point) 'org-marker)
15382		     (org-agenda-error)))
15383	 (buffer (marker-buffer marker))
15384	 (pos (marker-position marker)))
15385    (org-with-remote-undo buffer
15386      (with-current-buffer buffer
15387	(if (org-mode-p)
15388	    (save-excursion
15389	      (goto-char pos)
15390	      (org-remove-subtree-entries-from-agenda)
15391	      (org-back-to-heading t)
15392	      (org-archive-subtree))
15393	  (error "Archiving works only in Org-mode files"))))))
15394
15395(defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
15396  "Remove all lines in the agenda that correspond to a given subtree.
15397The subtree is the one in buffer BUF, starting at BEG and ending at END.
15398If this information is not given, the function uses the tree at point."
15399  (let ((buf (or buf (current-buffer))) m p)
15400    (save-excursion
15401      (unless (and beg end)
15402	(org-back-to-heading t)
15403	(setq beg (point))
15404	(org-end-of-subtree t)
15405	(setq end (point)))
15406      (set-buffer (get-buffer org-agenda-buffer-name))
15407      (save-excursion
15408	(goto-char (point-max))
15409	(beginning-of-line 1)
15410	(while (not (bobp))
15411	  (when (and (setq m (get-text-property (point) 'org-marker))
15412		     (equal buf (marker-buffer m))
15413		     (setq p (marker-position m))
15414		     (>= p beg)
15415		     (<= p end))
15416	    (let (buffer-read-only)
15417	      (delete-region (point-at-bol) (1+ (point-at-eol)))))
15418	  (beginning-of-line 0))))))
15419
15420(defun org-agenda-open-link ()
15421  "Follow the link in the current line, if any."
15422  (interactive)
15423  (let ((eol (point-at-eol)))
15424    (save-excursion
15425      (if (or (re-search-forward org-bracket-link-regexp eol t)
15426	      (re-search-forward org-angle-link-re eol t)
15427	      (re-search-forward org-plain-link-re eol t))
15428	  (call-interactively 'org-open-at-point)
15429	(error "No link in current line")))))
15430
15431(defun org-agenda-switch-to (&optional delete-other-windows)
15432  "Go to the Org-mode file which contains the item at point."
15433  (interactive)
15434  (let* ((marker (or (get-text-property (point) 'org-marker)
15435		     (org-agenda-error)))
15436	 (buffer (marker-buffer marker))
15437	 (pos (marker-position marker)))
15438    (switch-to-buffer buffer)
15439    (and delete-other-windows (delete-other-windows))
15440    (widen)
15441    (goto-char pos)
15442    (when (org-mode-p)
15443      (org-show-context 'agenda)
15444      (save-excursion
15445	(and (outline-next-heading)
15446	     (org-flag-heading nil))))))  ; show the next heading
15447
15448(defun org-agenda-goto-mouse (ev)
15449  "Go to the Org-mode file which contains the item at the mouse click."
15450  (interactive "e")
15451  (mouse-set-point ev)
15452  (org-agenda-goto))
15453
15454(defun org-agenda-show ()
15455  "Display the Org-mode file which contains the item at point."
15456  (interactive)
15457  (let ((win (selected-window)))
15458    (org-agenda-goto t)
15459    (select-window win)))
15460
15461(defun org-agenda-recenter (arg)
15462  "Display the Org-mode file which contains the item at point and recenter."
15463  (interactive "P")
15464  (let ((win (selected-window)))
15465    (org-agenda-goto t)
15466    (recenter arg)
15467    (select-window win)))
15468
15469(defun org-agenda-show-mouse (ev)
15470  "Display the Org-mode file which contains the item at the mouse click."
15471  (interactive "e")
15472  (mouse-set-point ev)
15473  (org-agenda-show))
15474
15475(defun org-agenda-check-no-diary ()
15476  "Check if the entry is a diary link and abort if yes."
15477  (if (get-text-property (point) 'org-agenda-diary-link)
15478      (org-agenda-error)))
15479
15480(defun org-agenda-error ()
15481  (error "Command not allowed in this line"))
15482
15483(defun org-agenda-tree-to-indirect-buffer ()
15484  "Show the subtree corresponding to the current entry in an indirect buffer.
15485This calls the command `org-tree-to-indirect-buffer' from the original
15486Org-mode buffer.
15487With numerical prefix arg ARG, go up to this level and then take that tree.
15488With a C-u prefix, make a separate frame for this tree (i.e. don't use the
15489dedicated frame)."
15490  (interactive)
15491  (org-agenda-check-no-diary)
15492  (let* ((marker (or (get-text-property (point) 'org-marker)
15493		     (org-agenda-error)))
15494	 (buffer (marker-buffer marker))
15495	 (pos (marker-position marker)))
15496    (with-current-buffer buffer
15497      (save-excursion
15498	(goto-char pos)
15499	(call-interactively 'org-tree-to-indirect-buffer)))))
15500
15501(defvar org-last-heading-marker (make-marker)
15502  "Marker pointing to the headline that last changed its TODO state
15503by a remote command from the agenda.")
15504
15505(defun org-agenda-todo (&optional arg)
15506  "Cycle TODO state of line at point, also in Org-mode file.
15507This changes the line at point, all other lines in the agenda referring to
15508the same tree node, and the headline of the tree node in the Org-mode file."
15509  (interactive "P")
15510  (org-agenda-check-no-diary)
15511  (let* ((col (current-column))
15512	 (marker (or (get-text-property (point) 'org-marker)
15513		     (org-agenda-error)))
15514	 (buffer (marker-buffer marker))
15515	 (pos (marker-position marker))
15516	 (hdmarker (get-text-property (point) 'org-hd-marker))
15517	 (buffer-read-only nil)
15518	 newhead)
15519    (org-with-remote-undo buffer
15520      (with-current-buffer buffer
15521	(widen)
15522	(goto-char pos)
15523	(org-show-context 'agenda)
15524	(save-excursion
15525	  (and (outline-next-heading)
15526	       (org-flag-heading nil)))   ; show the next heading
15527	(org-todo arg)
15528	(and (bolp) (forward-char 1))
15529	(setq newhead (org-get-heading))
15530	(save-excursion
15531	  (org-back-to-heading)
15532	  (move-marker org-last-heading-marker (point))))
15533      (beginning-of-line 1)
15534      (save-excursion
15535	(org-agenda-change-all-lines newhead hdmarker 'fixface))
15536      (move-to-column col))))
15537
15538(defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
15539  "Change all lines in the agenda buffer which match HDMARKER.
15540The new content of the line will be NEWHEAD (as modified by
15541`org-format-agenda-item').  HDMARKER is checked with
15542`equal' against all `org-hd-marker' text properties in the file.
15543If FIXFACE is non-nil, the face of each item is modified acording to
15544the new TODO state."
15545  (let* ((buffer-read-only nil)
15546	 props m pl undone-face done-face finish new dotime cat tags)
15547    (save-excursion
15548      (goto-char (point-max))
15549      (beginning-of-line 1)
15550      (while (not finish)
15551	(setq finish (bobp))
15552	(when (and (setq m (get-text-property (point) 'org-hd-marker))
15553		   (equal m hdmarker))
15554	  (setq props (text-properties-at (point))
15555		dotime (get-text-property (point) 'dotime)
15556		cat (get-text-property (point) 'org-category)
15557		tags (get-text-property (point) 'tags)
15558		new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
15559		pl (get-text-property (point) 'prefix-length)
15560		undone-face (get-text-property (point) 'undone-face)
15561		done-face (get-text-property (point) 'done-face))
15562	  (move-to-column pl)
15563	  (cond
15564	   ((equal new "")
15565	    (beginning-of-line 1)
15566	    (and (looking-at ".*\n?") (replace-match "")))
15567	   ((looking-at ".*")
15568	    (replace-match new t t)
15569	    (beginning-of-line 1)
15570	    (add-text-properties (point-at-bol) (point-at-eol) props)
15571	    (when fixface
15572	      (add-text-properties
15573	       (point-at-bol) (point-at-eol)
15574	       (list 'face
15575		     (if org-last-todo-state-is-todo
15576			 undone-face done-face))))
15577	    (org-agenda-highlight-todo 'line)
15578	    (beginning-of-line 1))
15579	   (t (error "Line update did not work"))))
15580	(beginning-of-line 0)))
15581    (org-finalize-agenda)))
15582
15583;; FIXME: allow negative value for org-agenda-align-tags-to-column
15584;; See the code in set-tags for the way to do this.
15585(defun org-agenda-align-tags (&optional line)
15586  "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
15587  (let ((buffer-read-only))
15588    (save-excursion
15589      (goto-char (if line (point-at-bol) (point-min)))
15590      (while (re-search-forward "\\([ \t]+\\):[a-zA-Z0-9_@:]+:[ \t]*$"
15591				(if line (point-at-eol) nil) t)
15592	(delete-region (match-beginning 1) (match-end 1))
15593	(goto-char (match-beginning 1))
15594	(insert (org-add-props
15595		    (make-string (max 1 (- org-agenda-align-tags-to-column
15596					   (current-column))) ?\ )
15597		    (text-properties-at (point))))))))
15598
15599(defun org-agenda-priority-up ()
15600  "Increase the priority of line at point, also in Org-mode file."
15601  (interactive)
15602  (org-agenda-priority 'up))
15603
15604(defun org-agenda-priority-down ()
15605  "Decrease the priority of line at point, also in Org-mode file."
15606  (interactive)
15607  (org-agenda-priority 'down))
15608
15609(defun org-agenda-priority (&optional force-direction)
15610  "Set the priority of line at point, also in Org-mode file.
15611This changes the line at point, all other lines in the agenda referring to
15612the same tree node, and the headline of the tree node in the Org-mode file."
15613  (interactive)
15614  (org-agenda-check-no-diary)
15615  (let* ((marker (or (get-text-property (point) 'org-marker)
15616		     (org-agenda-error)))
15617	 (buffer (marker-buffer marker))
15618	 (pos (marker-position marker))
15619	 (hdmarker (get-text-property (point) 'org-hd-marker))
15620	 (buffer-read-only nil)
15621	 newhead)
15622    (org-with-remote-undo buffer
15623      (with-current-buffer buffer
15624	(widen)
15625	(goto-char pos)
15626	(org-show-context 'agenda)
15627	(save-excursion
15628	  (and (outline-next-heading)
15629	       (org-flag-heading nil)))   ; show the next heading
15630	(funcall 'org-priority force-direction)
15631	(end-of-line 1)
15632	(setq newhead (org-get-heading)))
15633      (org-agenda-change-all-lines newhead hdmarker)
15634      (beginning-of-line 1))))
15635
15636(defun org-get-tags-at (&optional pos)
15637  "Get a list of all headline tags applicable at POS.
15638POS defaults to point.  If tags are inherited, the list contains
15639the targets in the same sequence as the headlines appear, i.e.
15640the tags of the current headline come last."
15641  (interactive)
15642  (let (tags)
15643    (save-excursion
15644      (save-restriction
15645	(widen)
15646	(goto-char (or pos (point)))
15647	(save-match-data
15648	  (org-back-to-heading t)
15649	  (condition-case nil
15650	      (while t
15651		(if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
15652		    (setq tags (append (org-split-string
15653					(org-match-string-no-properties 1) ":")
15654				       tags)))
15655	      (or org-use-tag-inheritance (error ""))
15656	      (org-up-heading-all 1))
15657	    (error nil))))
15658      tags)))
15659
15660;; FIXME: should fix the tags property of the agenda line.
15661(defun org-agenda-set-tags ()
15662  "Set tags for the current headline."
15663  (interactive)
15664  (org-agenda-check-no-diary)
15665  (org-agenda-show)   ;;; FIXME This is a stupid hack and should not be needed
15666  (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
15667                       (org-agenda-error)))
15668	 (buffer (marker-buffer hdmarker))
15669	 (pos (marker-position hdmarker))
15670	 (buffer-read-only nil)
15671	 newhead)
15672    (org-with-remote-undo buffer
15673      (with-current-buffer buffer
15674	(widen)
15675	(goto-char pos)
15676	(org-show-context 'agenda)
15677	(save-excursion
15678	  (and (outline-next-heading)
15679	       (org-flag-heading nil)))   ; show the next heading
15680	(call-interactively 'org-set-tags)
15681	(end-of-line 1)
15682	(setq newhead (org-get-heading)))
15683      (org-agenda-change-all-lines newhead hdmarker)
15684      (beginning-of-line 1))))
15685
15686(defun org-agenda-toggle-archive-tag ()
15687  "Toggle the archive tag for the current entry."
15688  (interactive)
15689  (org-agenda-check-no-diary)
15690  (org-agenda-show)   ;;; FIXME This is a stupid hack and should not be needed
15691  (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
15692                       (org-agenda-error)))
15693	 (buffer (marker-buffer hdmarker))
15694	 (pos (marker-position hdmarker))
15695	 (buffer-read-only nil)
15696	 newhead)
15697    (org-with-remote-undo buffer
15698      (with-current-buffer buffer
15699	(widen)
15700	(goto-char pos)
15701	(org-show-context 'agenda)
15702	(save-excursion
15703	  (and (outline-next-heading)
15704	       (org-flag-heading nil)))   ; show the next heading
15705	(call-interactively 'org-toggle-archive-tag)
15706	(end-of-line 1)
15707	(setq newhead (org-get-heading)))
15708      (org-agenda-change-all-lines newhead hdmarker)
15709      (beginning-of-line 1))))
15710
15711(defun org-agenda-date-later (arg &optional what)
15712  "Change the date of this item to one day later."
15713  (interactive "p")
15714  (org-agenda-check-type t 'agenda 'timeline)
15715  (org-agenda-check-no-diary)
15716  (let* ((marker (or (get-text-property (point) 'org-marker)
15717		     (org-agenda-error)))
15718	 (buffer (marker-buffer marker))
15719	 (pos (marker-position marker)))
15720    (org-with-remote-undo buffer
15721     (with-current-buffer buffer
15722       (widen)
15723       (goto-char pos)
15724       (if (not (org-at-timestamp-p))
15725	   (error "Cannot find time stamp"))
15726       (org-timestamp-change arg (or what 'day)))
15727     (org-agenda-show-new-time marker org-last-changed-timestamp))
15728    (message "Time stamp changed to %s" org-last-changed-timestamp)))
15729
15730(defun org-agenda-date-earlier (arg &optional what)
15731  "Change the date of this item to one day earlier."
15732  (interactive "p")
15733  (org-agenda-date-later (- arg) what))
15734
15735(defun org-agenda-show-new-time (marker stamp)
15736  "Show new date stamp via text properties."
15737  ;; We use text properties to make this undoable
15738  (let ((buffer-read-only nil))
15739    (setq stamp (concat " => " stamp))
15740    (save-excursion
15741      (goto-char (point-max))
15742      (while (not (bobp))
15743	(when (equal marker (get-text-property (point) 'org-marker))
15744	  (move-to-column (- (window-width) (length stamp)) t)
15745          (if (featurep 'xemacs)
15746	      ;; Use `duplicable' property to trigger undo recording
15747              (let ((ex (make-extent nil nil))
15748                    (gl (make-glyph stamp)))
15749                (set-glyph-face gl 'secondary-selection)
15750                (set-extent-properties
15751                 ex (list 'invisible t 'end-glyph gl 'duplicable t))
15752                (insert-extent ex (1- (point)) (point-at-eol)))
15753            (add-text-properties
15754             (1- (point)) (point-at-eol)
15755	     (list 'display (org-add-props stamp nil
15756			      'face 'secondary-selection))))
15757	  (beginning-of-line 1))
15758	(beginning-of-line 0)))))
15759
15760(defun org-agenda-date-prompt (arg)
15761  "Change the date of this item.  Date is prompted for, with default today.
15762The prefix ARG is passed to the `org-time-stamp' command and can therefore
15763be used to request time specification in the time stamp."
15764  (interactive "P")
15765  (org-agenda-check-type t 'agenda 'timeline)
15766  (org-agenda-check-no-diary)
15767  (let* ((marker (or (get-text-property (point) 'org-marker)
15768		     (org-agenda-error)))
15769	 (buffer (marker-buffer marker))
15770	 (pos (marker-position marker)))
15771    (org-with-remote-undo buffer
15772      (with-current-buffer buffer
15773	(widen)
15774	(goto-char pos)
15775	(if (not (org-at-timestamp-p))
15776	    (error "Cannot find time stamp"))
15777	(org-time-stamp arg)
15778	(message "Time stamp changed to %s" org-last-changed-timestamp)))))
15779
15780(defun org-agenda-schedule (arg)
15781  "Schedule the item at point."
15782  (interactive "P")
15783  (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
15784  (org-agenda-check-no-diary)
15785  (let* ((marker (or (get-text-property (point) 'org-marker)
15786		     (org-agenda-error)))
15787	 (buffer (marker-buffer marker))
15788	 (pos (marker-position marker))
15789	 (org-insert-labeled-timestamps-at-point nil)
15790	 ts)
15791    (org-with-remote-undo buffer
15792      (with-current-buffer buffer
15793	(widen)
15794	(goto-char pos)
15795	(setq ts (org-schedule))
15796	(message "Item scheduled for %s" ts)))))
15797
15798(defun org-agenda-deadline (arg)
15799  "Schedule the item at point."
15800  (interactive "P")
15801  (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
15802  (org-agenda-check-no-diary)
15803  (let* ((marker (or (get-text-property (point) 'org-marker)
15804		     (org-agenda-error)))
15805	 (buffer (marker-buffer marker))
15806	 (pos (marker-position marker))
15807	 (org-insert-labeled-timestamps-at-point nil)
15808	 ts)
15809    (org-with-remote-undo buffer
15810      (with-current-buffer buffer
15811	(widen)
15812	(goto-char pos)
15813	(setq ts (org-deadline))
15814	(message "Deadline for this item set to %s" ts)))))
15815
15816(defun org-get-heading ()
15817  "Return the heading of the current entry, without the stars."
15818  (save-excursion
15819    (org-back-to-heading t)
15820    (if (looking-at "\\*+[ \t]+\\([^\r\n]*\\)")	(match-string 1) "")))
15821
15822(defun org-agenda-clock-in (&optional arg)
15823  "Start the clock on the currently selected item."
15824  (interactive "P")
15825  (org-agenda-check-no-diary)
15826  (let* ((marker (or (get-text-property (point) 'org-marker)
15827		     (org-agenda-error)))
15828	 (pos (marker-position marker)))
15829    (org-with-remote-undo (marker-buffer marker)
15830      (with-current-buffer (marker-buffer marker)
15831	(widen)
15832	(goto-char pos)
15833	(org-clock-in)))))
15834
15835(defun org-agenda-clock-out (&optional arg)
15836  "Stop the currently running clock."
15837  (interactive "P")
15838  (unless (marker-buffer org-clock-marker)
15839    (error "No running clock"))
15840  (org-with-remote-undo (marker-buffer org-clock-marker)
15841    (org-clock-out)))
15842
15843(defun org-agenda-clock-cancel (&optional arg)
15844  "Cancel the currently running clock."
15845  (interactive "P")
15846  (unless (marker-buffer org-clock-marker)
15847    (error "No running clock"))
15848  (org-with-remote-undo (marker-buffer org-clock-marker)
15849    (org-clock-cancel)))
15850
15851(defun org-agenda-diary-entry ()
15852  "Make a diary entry, like the `i' command from the calendar.
15853All the standard commands work: block, weekly etc."
15854  (interactive)
15855  (org-agenda-check-type t 'agenda 'timeline)
15856  (require 'diary-lib)
15857  (let* ((char (progn
15858		 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
15859		 (read-char-exclusive)))
15860	 (cmd (cdr (assoc char
15861			  '((?d . insert-diary-entry)
15862			    (?w . insert-weekly-diary-entry)
15863			    (?m . insert-monthly-diary-entry)
15864			    (?y . insert-yearly-diary-entry)
15865			    (?a . insert-anniversary-diary-entry)
15866			    (?b . insert-block-diary-entry)
15867			    (?c . insert-cyclic-diary-entry)))))
15868	 (oldf (symbol-function 'calendar-cursor-to-date))
15869;	 (buf (get-file-buffer (substitute-in-file-name diary-file)))
15870	 (point (point))
15871	 (mark (or (mark t) (point))))
15872    (unless cmd
15873      (error "No command associated with <%c>" char))
15874    (unless (and (get-text-property point 'day)
15875		 (or (not (equal ?b char))
15876		     (get-text-property mark 'day)))
15877      (error "Don't know which date to use for diary entry"))
15878    ;; We implement this by hacking the `calendar-cursor-to-date' function
15879    ;; and the `calendar-mark-ring' variable.  Saves a lot of code.
15880    (let ((calendar-mark-ring
15881	   (list (calendar-gregorian-from-absolute
15882		  (or (get-text-property mark 'day)
15883		      (get-text-property point 'day))))))
15884      (unwind-protect
15885	  (progn
15886	    (fset 'calendar-cursor-to-date
15887		  (lambda (&optional error)
15888		    (calendar-gregorian-from-absolute
15889		     (get-text-property point 'day))))
15890	      (call-interactively cmd))
15891	(fset 'calendar-cursor-to-date oldf)))))
15892
15893
15894(defun org-agenda-execute-calendar-command (cmd)
15895  "Execute a calendar command from the agenda, with the date associated to
15896the cursor position."
15897  (org-agenda-check-type t 'agenda 'timeline)
15898  (require 'diary-lib)
15899  (unless (get-text-property (point) 'day)
15900    (error "Don't know which date to use for calendar command"))
15901  (let* ((oldf (symbol-function 'calendar-cursor-to-date))
15902	 (point (point))
15903	 (date (calendar-gregorian-from-absolute
15904		(get-text-property point 'day)))
15905         ;; the following 3 vars are needed in the calendar
15906	 (displayed-day (extract-calendar-day date))
15907	 (displayed-month (extract-calendar-month date))
15908	 (displayed-year (extract-calendar-year date)))
15909      (unwind-protect
15910	  (progn
15911	    (fset 'calendar-cursor-to-date
15912		  (lambda (&optional error)
15913		    (calendar-gregorian-from-absolute
15914		     (get-text-property point 'day))))
15915	    (call-interactively cmd))
15916	(fset 'calendar-cursor-to-date oldf))))
15917
15918(defun org-agenda-phases-of-moon ()
15919  "Display the phases of the moon for the 3 months around the cursor date."
15920  (interactive)
15921  (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
15922
15923(defun org-agenda-holidays ()
15924  "Display the holidays for the 3 months around the cursor date."
15925  (interactive)
15926  (org-agenda-execute-calendar-command 'list-calendar-holidays))
15927
15928(defun org-agenda-sunrise-sunset (arg)
15929  "Display sunrise and sunset for the cursor date.
15930Latitude and longitude can be specified with the variables
15931`calendar-latitude' and `calendar-longitude'.  When called with prefix
15932argument, latitude and longitude will be prompted for."
15933  (interactive "P")
15934  (let ((calendar-longitude (if arg nil calendar-longitude))
15935	(calendar-latitude  (if arg nil calendar-latitude))
15936	(calendar-location-name
15937	 (if arg "the given coordinates" calendar-location-name)))
15938    (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
15939
15940(defun org-agenda-goto-calendar ()
15941  "Open the Emacs calendar with the date at the cursor."
15942  (interactive)
15943  (org-agenda-check-type t 'agenda 'timeline)
15944  (let* ((day (or (get-text-property (point) 'day)
15945		  (error "Don't know which date to open in calendar")))
15946	 (date (calendar-gregorian-from-absolute day))
15947	 (calendar-move-hook nil)
15948	 (view-calendar-holidays-initially nil)
15949	 (view-diary-entries-initially nil))
15950    (calendar)
15951    (calendar-goto-date date)))
15952
15953(defun org-calendar-goto-agenda ()
15954  "Compute the Org-mode agenda for the calendar date displayed at the cursor.
15955This is a command that has to be installed in `calendar-mode-map'."
15956  (interactive)
15957  (org-agenda-list nil (calendar-absolute-from-gregorian
15958			(calendar-cursor-to-date))
15959		   nil))
15960
15961(defun org-agenda-convert-date ()
15962  (interactive)
15963  (org-agenda-check-type t 'agenda 'timeline)
15964  (let ((day (get-text-property (point) 'day))
15965	date s)
15966    (unless day
15967      (error "Don't know which date to convert"))
15968    (setq date (calendar-gregorian-from-absolute day))
15969    (setq s (concat
15970	     "Gregorian:  " (calendar-date-string date) "\n"
15971	     "ISO:        " (calendar-iso-date-string date) "\n"
15972	     "Day of Yr:  " (calendar-day-of-year-string date) "\n"
15973	     "Julian:     " (calendar-julian-date-string date) "\n"
15974	     "Astron. JD: " (calendar-astro-date-string date)
15975	     " (Julian date number at noon UTC)\n"
15976	     "Hebrew:     " (calendar-hebrew-date-string date) " (until sunset)\n"
15977	     "Islamic:    " (calendar-islamic-date-string date) " (until sunset)\n"
15978	     "French:     " (calendar-french-date-string date) "\n"
15979	     "Mayan:      " (calendar-mayan-date-string date) "\n"
15980	     "Coptic:     " (calendar-coptic-date-string date) "\n"
15981	     "Ethiopic:   " (calendar-ethiopic-date-string date) "\n"
15982	     "Persian:    " (calendar-persian-date-string date) "\n"
15983	     "Chinese:    " (calendar-chinese-date-string date) "\n"))
15984    (with-output-to-temp-buffer "*Dates*"
15985      (princ s))
15986    (if (fboundp 'fit-window-to-buffer)
15987	(fit-window-to-buffer (get-buffer-window "*Dates*")))))
15988
15989
15990;;;; Embedded LaTeX
15991
15992(defvar org-cdlatex-mode-map (make-sparse-keymap)
15993  "Keymap for the minor `org-cdlatex-mode'.")
15994
15995(define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
15996(define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
15997(define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
15998(define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
15999(define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16000
16001(defvar org-cdlatex-texmathp-advice-is-done nil
16002  "Flag remembering if we have applied the advice to texmathp already.")
16003
16004(define-minor-mode org-cdlatex-mode
16005  "Toggle the minor `org-cdlatex-mode'.
16006This mode supports entering LaTeX environment and math in LaTeX fragments
16007in Org-mode.
16008\\{org-cdlatex-mode-map}"
16009  nil " OCDL" nil
16010  (when org-cdlatex-mode (require 'cdlatex))
16011  (unless org-cdlatex-texmathp-advice-is-done
16012    (setq org-cdlatex-texmathp-advice-is-done t)
16013    (defadvice texmathp (around org-math-always-on activate)
16014      "Always return t in org-mode buffers.
16015This is because we want to insert math symbols without dollars even outside
16016the LaTeX math segments.  If Orgmode thinks that point is actually inside
16017en embedded LaTeX fragement, let texmathp do its job.
16018\\[org-cdlatex-mode-map]"
16019      (interactive)
16020      (let (p)
16021	(cond
16022	 ((not (org-mode-p)) ad-do-it)
16023	 ((eq this-command 'cdlatex-math-symbol)
16024	  (setq ad-return-value t
16025		texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16026	 (t
16027	  (let ((p (org-inside-LaTeX-fragment-p)))
16028	    (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16029		(setq ad-return-value t
16030		      texmathp-why '("Org-mode embedded math" . 0))
16031	      (if p ad-do-it)))))))))
16032
16033(defun turn-on-org-cdlatex ()
16034  "Unconditionally turn on `org-cdlatex-mode'."
16035  (org-cdlatex-mode 1))
16036
16037(defun org-inside-LaTeX-fragment-p ()
16038  "Test if point is inside a LaTeX fragment.
16039I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16040sequence appearing also before point.
16041Even though the matchers for math are configurable, this function assumes
16042that \\begin, \\(, \\[, and $$ are always used.  Only the single dollar
16043delimiters are skipped when they have been removed by customization.
16044The return value is nil, or a cons cell with the delimiter and
16045and the position of this delimiter.
16046
16047This function does a reasonably good job, but can locally be fooled by
16048for example currency specifications.  For example it will assume being in
16049inline math after \"$22.34\".  The LaTeX fragment formatter will only format
16050fragments that are properly closed, but during editing, we have to live
16051with the uncertainty caused by missing closing delimiters.  This function
16052looks only before point, not after."
16053  (catch 'exit
16054    (let ((pos (point))
16055	  (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16056	  (lim (progn
16057		 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16058		 (point)))
16059	  dd-on str (start 0) m re)
16060      (goto-char pos)
16061      (when dodollar
16062	(setq str (concat (buffer-substring lim (point)) "\000 X$.")
16063	      re (nth 1 (assoc "$" org-latex-regexps)))
16064	(while (string-match re str start)
16065	  (cond
16066	   ((= (match-end 0) (length str))
16067	    (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
16068	   ((= (match-end 0) (- (length str) 5))
16069	    (throw 'exit nil))
16070	   (t (setq start (match-end 0))))))
16071      (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16072	(goto-char pos)
16073	(and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16074	(and (match-beginning 2) (throw 'exit nil))
16075	;; count $$
16076	(while (re-search-backward "\\$\\$" lim t)
16077	  (setq dd-on (not dd-on)))
16078	(goto-char pos)
16079	(if dd-on (cons "$$" m))))))
16080
16081
16082(defun org-try-cdlatex-tab ()
16083  "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16084It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16085  - inside a LaTeX fragment, or
16086  - after the first word in a line, where an abbreviation expansion could
16087    insert a LaTeX environment."
16088  (when org-cdlatex-mode
16089    (cond
16090     ((save-excursion
16091	(skip-chars-backward "a-zA-Z0-9*")
16092	(skip-chars-backward " \t")
16093	(bolp))
16094      (cdlatex-tab) t)
16095     ((org-inside-LaTeX-fragment-p)
16096      (cdlatex-tab) t)
16097     (t nil))))
16098
16099(defun org-cdlatex-underscore-caret (&optional arg)
16100  "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16101Revert to the normal definition outside of these fragments."
16102  (interactive "P")
16103  (if (org-inside-LaTeX-fragment-p)
16104      (call-interactively 'cdlatex-sub-superscript)
16105    (let (org-cdlatex-mode)
16106      (call-interactively (key-binding (vector last-input-event))))))
16107
16108(defun org-cdlatex-math-modify (&optional arg)
16109  "Execute `cdlatex-math-modify' in LaTeX fragments.
16110Revert to the normal definition outside of these fragments."
16111  (interactive "P")
16112  (if (org-inside-LaTeX-fragment-p)
16113      (call-interactively 'cdlatex-math-modify)
16114    (let (org-cdlatex-mode)
16115      (call-interactively (key-binding (vector last-input-event))))))
16116
16117(defvar org-latex-fragment-image-overlays nil
16118  "List of overlays carrying the images of latex fragments.")
16119(make-variable-buffer-local 'org-latex-fragment-image-overlays)
16120
16121(defun org-remove-latex-fragment-image-overlays ()
16122  "Remove all overlays with LaTeX fragment images in current buffer."
16123  (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
16124  (setq org-latex-fragment-image-overlays nil))
16125
16126(defun org-preview-latex-fragment (&optional subtree)
16127  "Preview the LaTeX fragment at point, or all locally or globally.
16128If the cursor is in a LaTeX fragment, create the image and overlay
16129it over the source code.  If there is no fragment at point, display
16130all fragments in the current text, from one headline to the next.  With
16131prefix SUBTREE, display all fragments in the current subtree.  With a
16132double prefix `C-u C-u', or when the cursor is before the first headline,
16133display all fragments in the buffer.
16134The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16135  (interactive "P")
16136  (org-remove-latex-fragment-image-overlays)
16137  (save-excursion
16138    (save-restriction
16139      (let (beg end at msg)
16140	(cond
16141	 ((or (equal subtree '(16))
16142	      (not (save-excursion
16143		     (re-search-backward (concat "^" outline-regexp) nil t))))
16144	  (setq beg (point-min) end (point-max)
16145		msg "Creating images for buffer...%s"))
16146	 ((equal subtree '(4))
16147	  (org-back-to-heading)
16148	  (setq beg (point) end (org-end-of-subtree t)
16149		msg "Creating images for subtree...%s"))
16150	 (t
16151	  (if (setq at (org-inside-LaTeX-fragment-p))
16152	      (goto-char (max (point-min) (- (cdr at) 2)))
16153	    (org-back-to-heading))
16154	  (setq beg (point) end (progn (outline-next-heading) (point))
16155		msg (if at "Creating image...%s"
16156		      "Creating images for entry...%s"))))
16157	(message msg "")
16158	(narrow-to-region beg end)
16159	(org-format-latex
16160	 (concat "ltxpng/" (file-name-sans-extension
16161			    (file-name-nondirectory
16162			     buffer-file-name)))
16163	 default-directory 'overlays msg at)
16164      (message msg "done.  Use `C-c C-c' to remove images.")))))
16165
16166(defvar org-latex-regexps
16167  '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16168    ;; ("$" "\\([ 	(]\\|^\\)\\(\\(\\([$]\\)\\([^ 	\r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ 	\r\n,.$]\\)\\4\\)\\)\\([ 	.,?;:'\")]\\|$\\)" 2 nil)
16169    ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16170    ("$" "\\([^$]\\)\\(\\(\\$\\([^ 	\r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ 	\r\n,.$]\\)\\$\\)\\)\\([ 	.,?;:'\")\000]\\|$\\)" 2 nil)
16171    ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16172    ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
16173    ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
16174  "Regular expressions for matching embedded LaTeX.")
16175
16176(defun org-format-latex (prefix &optional dir overlays msg at)
16177  "Replace LaTeX fragments with links to an image, and produce images."
16178  (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16179  (let* ((prefixnodir (file-name-nondirectory prefix))
16180	 (absprefix (expand-file-name prefix dir))
16181	 (todir (file-name-directory absprefix))
16182	 (opt org-format-latex-options)
16183	 (matchers (plist-get opt :matchers))
16184	 (re-list org-latex-regexps)
16185	 (cnt 0) txt link beg end re e checkdir
16186	 m n block linkfile movefile ov)
16187    ;; Check if there are old images files with this prefix, and remove them
16188    (when (file-directory-p todir)
16189      (mapc 'delete-file
16190	    (directory-files
16191	     todir 'full
16192	     (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
16193    ;; Check the different regular expressions
16194    (while (setq e (pop re-list))
16195      (setq m (car e) re (nth 1 e) n (nth 2 e)
16196	    block (if (nth 3 e) "\n\n" ""))
16197      (when (member m matchers)
16198	(goto-char (point-min))
16199	(while (re-search-forward re nil t)
16200	  (when (or (not at) (equal (cdr at) (match-beginning n)))
16201	    (setq txt (match-string n)
16202		  beg (match-beginning n) end (match-end n)
16203		  cnt (1+ cnt)
16204		  linkfile (format "%s_%04d.png" prefix cnt)
16205		  movefile (format "%s_%04d.png" absprefix cnt)
16206		  link (concat block "[[file:" linkfile "]]" block))
16207	    (if msg (message msg cnt))
16208	    (goto-char beg)
16209	    (unless checkdir ; make sure the directory exists
16210	      (setq checkdir t)
16211	      (or (file-directory-p todir) (make-directory todir)))
16212	    (org-create-formula-image
16213	     txt movefile opt)
16214	    (if overlays
16215		(progn
16216		  (setq ov (org-make-overlay beg end))
16217		  (if (featurep 'xemacs)
16218		      (progn
16219			(org-overlay-put ov 'invisible t)
16220			(org-overlay-put
16221			 ov 'end-glyph
16222			 (make-glyph (vector 'png :file movefile))))
16223		    (org-overlay-put
16224		     ov 'display
16225		     (list 'image :type 'png :file movefile :ascent 'center)))
16226		  (push ov org-latex-fragment-image-overlays)
16227		  (goto-char end))
16228	      (delete-region beg end)
16229	      (insert link))))))))
16230
16231;; This function borrows from Ganesh Swami's latex2png.el
16232(defun org-create-formula-image (string tofile options)
16233  (let* ((tmpdir (if (featurep 'xemacs)
16234		     (temp-directory)
16235		   temporary-file-directory))
16236	 (texfilebase (make-temp-name
16237		       (expand-file-name "orgtex" tmpdir)))
16238
16239;(texfilebase (make-temp-file "orgtex"))
16240;	 (dummy (delete-file texfilebase))
16241	 (texfile (concat texfilebase ".tex"))
16242	 (dvifile (concat texfilebase ".dvi"))
16243	 (pngfile (concat texfilebase ".png"))
16244	 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
16245	 (fg (or (plist-get options :foreground) "Black"))
16246	 (bg (or (plist-get options :background) "Transparent")))
16247    (with-temp-file texfile
16248      (insert "\\documentclass{article}
16249\\usepackage{fullpage}
16250\\usepackage{amssymb}
16251\\usepackage[usenames]{color}
16252\\usepackage{amsmath}
16253\\usepackage{latexsym}
16254\\usepackage[mathscr]{eucal}
16255\\pagestyle{empty}
16256\\begin{document}\n" string "\n\\end{document}\n"))
16257    (let ((dir default-directory))
16258      (condition-case nil
16259	  (progn
16260	    (cd tmpdir)
16261	    (call-process "latex" nil nil nil texfile))
16262	(error nil))
16263      (cd dir))
16264    (if (not (file-exists-p dvifile))
16265	(progn (message "Failed to create dvi file from %s" texfile) nil)
16266      (call-process "dvipng" nil nil nil
16267		    "-E" "-fg" fg "-bg" bg
16268		    "-x" scale "-y" scale "-T" "tight"
16269		    "-o" pngfile
16270		    dvifile)
16271      (if (not (file-exists-p pngfile))
16272	  (progn (message "Failed to create png file from %s" texfile) nil)
16273	;; Use the requested file name and clean up
16274	(copy-file pngfile tofile 'replace)
16275	(loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16276	      (delete-file (concat texfilebase e)))
16277	pngfile))))
16278
16279;;;; Exporting
16280
16281;;; Variables, constants, and parameter plists
16282
16283(defconst org-level-max 20)
16284
16285(defvar org-export-html-preamble nil
16286  "Preamble, to be inserted just after <body>.  Set by publishing functions.")
16287(defvar org-export-html-postamble nil
16288  "Preamble, to be inserted just before </body>.  Set by publishing functions.")
16289(defvar org-export-html-auto-preamble t
16290  "Should default preamble be inserted?  Set by publishing functions.")
16291(defvar org-export-html-auto-postamble t
16292  "Should default postamble be inserted?  Set by publishing functions.")
16293(defvar org-current-export-file nil) ; dynamically scoped parameter
16294(defvar org-current-export-dir nil) ; dynamically scoped parameter
16295
16296
16297(defconst org-export-plist-vars
16298  '((:language             . org-export-default-language)
16299    (:customtime           . org-display-custom-times)
16300    (:headline-levels      . org-export-headline-levels)
16301    (:section-numbers      . org-export-with-section-numbers)
16302    (:table-of-contents    . org-export-with-toc)
16303    (:archived-trees       . org-export-with-archived-trees)
16304    (:emphasize            . org-export-with-emphasize)
16305    (:sub-superscript      . org-export-with-sub-superscripts)
16306    (:TeX-macros           . org-export-with-TeX-macros)
16307    (:LaTeX-fragments      . org-export-with-LaTeX-fragments)
16308    (:fixed-width          . org-export-with-fixed-width)
16309    (:timestamps           . org-export-with-timestamps)
16310    (:tables               . org-export-with-tables)
16311    (:table-auto-headline  . org-export-highlight-first-table-line)
16312    (:style                . org-export-html-style)
16313    (:convert-org-links    . org-export-html-link-org-files-as-html)
16314    (:inline-images        . org-export-html-inline-images)
16315    (:expand-quoted-html   . org-export-html-expand)
16316    (:timestamp            . org-export-html-with-timestamp)
16317    (:publishing-directory . org-export-publishing-directory)
16318    (:preamble             . org-export-html-preamble)
16319    (:postamble            . org-export-html-postamble)
16320    (:auto-preamble        . org-export-html-auto-preamble)
16321    (:auto-postamble       . org-export-html-auto-postamble)
16322    (:author               . user-full-name)
16323    (:email                . user-mail-address)))
16324
16325(defun org-default-export-plist ()
16326  "Return the property list with default settings for the export variables."
16327  (let ((l org-export-plist-vars) rtn e)
16328    (while (setq e (pop l))
16329      (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
16330    rtn))
16331
16332(defun org-infile-export-plist ()
16333  "Return the property list with file-local settings for export."
16334  (save-excursion
16335    (goto-char 0)
16336    (let ((re (org-make-options-regexp
16337	       '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
16338	  p key val text options)
16339      (while (re-search-forward re nil t)
16340	(setq key (org-match-string-no-properties 1)
16341	      val (org-match-string-no-properties 2))
16342	(cond
16343	 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
16344	 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
16345	 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
16346	 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
16347	 ((string-equal key "TEXT")
16348	  (setq text (if text (concat text "\n" val) val)))
16349	 ((string-equal key "OPTIONS") (setq options val))))
16350      (setq p (plist-put p :text text))
16351      (when options
16352	(let ((op '(("H"     . :headline-levels)
16353		    ("num"   . :section-numbers)
16354		    ("toc"   . :table-of-contents)
16355		    ("\\n"   . :preserve-breaks)
16356		    ("@"     . :expand-quoted-html)
16357		    (":"     . :fixed-width)
16358		    ("|"     . :tables)
16359		    ("^"     . :sub-superscript)
16360		    ("*"     . :emphasize)
16361		    ("TeX"   . :TeX-macros)
16362		    ("LaTeX" . :LaTeX-fragments)))
16363	      o)
16364	  (while (setq o (pop op))
16365	    (if (string-match (concat (regexp-quote (car o))
16366				      ":\\([^ \t\n\r;,.]*\\)")
16367			      options)
16368		(setq p (plist-put p (cdr o)
16369				   (car (read-from-string
16370					 (match-string 1 options)))))))))
16371      p)))
16372
16373(defun org-export-directory (type plist)
16374  (let* ((val (plist-get plist :publishing-directory))
16375	 (dir (if (listp val)
16376		  (or (cdr (assoc type val)) ".")
16377		val)))
16378    dir))
16379
16380(defun org-export-find-first-heading-line (list)
16381  "Remove all lines from LIST which are before the first headline."
16382  (let ((orig-list list)
16383	(re (concat "^" outline-regexp)))
16384    (while (and list
16385		(not (string-match re (car list))))
16386      (pop list))
16387    (or list orig-list)))
16388
16389(defun org-skip-comments (lines)
16390  "Skip lines starting with \"#\" and subtrees starting with COMMENT."
16391  (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
16392	(re2 "^\\(\\*+\\)[ \t\n\r]")
16393	rtn line level)
16394    (while (setq line (pop lines))
16395      (cond
16396       ((and (string-match re1 line)
16397	     (setq level (- (match-end 1) (match-beginning 1))))
16398	;; Beginning of a COMMENT subtree.  Skip it.
16399	(while (and (setq line (pop lines))
16400		    (or (not (string-match re2 line))
16401			(> (- (match-end 1) (match-beginning 1)) level))))
16402	(setq lines (cons line lines)))
16403       ((string-match "^#" line)
16404	;; an ordinary comment line
16405	)
16406       ((and org-export-table-remove-special-lines
16407	     (string-match "^[ \t]*|" line)
16408	     (or (string-match "^[ \t]*| *[!_^] *|" line)
16409		 (and (string-match "| *<[0-9]+> *|" line)
16410		      (not (string-match "| *[^ <|]" line)))))
16411	;; a special table line that should be removed
16412	)
16413       (t (setq rtn (cons line rtn)))))
16414    (nreverse rtn)))
16415
16416(defun org-export (&optional arg)
16417  (interactive)
16418  (let ((help "[t]   insert the export option template
16419\[v]   limit export to visible part of outline tree
16420
16421\[a] export as ASCII
16422\[h] export as HTML
16423\[b] export as HTML and browse immediately
16424\[x] export as XOXO
16425
16426\[i] export current file as iCalendar file
16427\[I] export all agenda files as iCalendar files
16428\[c] export agenda files into combined iCalendar file
16429
16430\[F] publish current file
16431\[P] publish current project
16432\[X] publish... (project will be prompted for)
16433\[A] publish all projects")
16434	(cmds
16435	 '((?t . org-insert-export-options-template)
16436	   (?v . org-export-visible)
16437	   (?a . org-export-as-ascii)
16438	   (?h . org-export-as-html)
16439	   (?b . org-export-as-html-and-open)
16440	   (?x . org-export-as-xoxo)
16441	   (?i . org-export-icalendar-this-file)
16442	   (?I . org-export-icalendar-all-agenda-files)
16443	   (?c . org-export-icalendar-combine-agenda-files)
16444	   (?F . org-publish-current-file)
16445	   (?P . org-publish-current-project)
16446	   (?X . org-publish)
16447	   (?A . org-publish-all)))
16448	r1 r2 ass)
16449    (save-window-excursion
16450      (delete-other-windows)
16451      (with-output-to-temp-buffer "*Org Export/Publishing Help*"
16452	(princ help))
16453      (message "Select command: ")
16454      (setq r1 (read-char-exclusive)))
16455    (setq r2 (if (< r1 27) (+ r1 96) r1))
16456    (if (setq ass (assq r2 cmds))
16457	(call-interactively (cdr ass))
16458      (error "No command associated with key %c" r1))))
16459
16460(defconst org-html-entities
16461  '(("nbsp")
16462    ("iexcl")
16463    ("cent")
16464    ("pound")
16465    ("curren")
16466    ("yen")
16467    ("brvbar")
16468    ("sect")
16469    ("uml")
16470    ("copy")
16471    ("ordf")
16472    ("laquo")
16473    ("not")
16474    ("shy")
16475    ("reg")
16476    ("macr")
16477    ("deg")
16478    ("plusmn")
16479    ("sup2")
16480    ("sup3")
16481    ("acute")
16482    ("micro")
16483    ("para")
16484    ("middot")
16485    ("odot"."o")
16486    ("star"."*")
16487    ("cedil")
16488    ("sup1")
16489    ("ordm")
16490    ("raquo")
16491    ("frac14")
16492    ("frac12")
16493    ("frac34")
16494    ("iquest")
16495    ("Agrave")
16496    ("Aacute")
16497    ("Acirc")
16498    ("Atilde")
16499    ("Auml")
16500    ("Aring") ("AA"."&Aring;")
16501    ("AElig")
16502    ("Ccedil")
16503    ("Egrave")
16504    ("Eacute")
16505    ("Ecirc")
16506    ("Euml")
16507    ("Igrave")
16508    ("Iacute")
16509    ("Icirc")
16510    ("Iuml")
16511    ("ETH")
16512    ("Ntilde")
16513    ("Ograve")
16514    ("Oacute")
16515    ("Ocirc")
16516    ("Otilde")
16517    ("Ouml")
16518    ("times")
16519    ("Oslash")
16520    ("Ugrave")
16521    ("Uacute")
16522    ("Ucirc")
16523    ("Uuml")
16524    ("Yacute")
16525    ("THORN")
16526    ("szlig")
16527    ("agrave")
16528    ("aacute")
16529    ("acirc")
16530    ("atilde")
16531    ("auml")
16532    ("aring")
16533    ("aelig")
16534    ("ccedil")
16535    ("egrave")
16536    ("eacute")
16537    ("ecirc")
16538    ("euml")
16539    ("igrave")
16540    ("iacute")
16541    ("icirc")
16542    ("iuml")
16543    ("eth")
16544    ("ntilde")
16545    ("ograve")
16546    ("oacute")
16547    ("ocirc")
16548    ("otilde")
16549    ("ouml")
16550    ("divide")
16551    ("oslash")
16552    ("ugrave")
16553    ("uacute")
16554    ("ucirc")
16555    ("uuml")
16556    ("yacute")
16557    ("thorn")
16558    ("yuml")
16559    ("fnof")
16560    ("Alpha")
16561    ("Beta")
16562    ("Gamma")
16563    ("Delta")
16564    ("Epsilon")
16565    ("Zeta")
16566    ("Eta")
16567    ("Theta")
16568    ("Iota")
16569    ("Kappa")
16570    ("Lambda")
16571    ("Mu")
16572    ("Nu")
16573    ("Xi")
16574    ("Omicron")
16575    ("Pi")
16576    ("Rho")
16577    ("Sigma")
16578    ("Tau")
16579    ("Upsilon")
16580    ("Phi")
16581    ("Chi")
16582    ("Psi")
16583    ("Omega")
16584    ("alpha")
16585    ("beta")
16586    ("gamma")
16587    ("delta")
16588    ("epsilon")
16589    ("varepsilon"."&epsilon;")
16590    ("zeta")
16591    ("eta")
16592    ("theta")
16593    ("iota")
16594    ("kappa")
16595    ("lambda")
16596    ("mu")
16597    ("nu")
16598    ("xi")
16599    ("omicron")
16600    ("pi")
16601    ("rho")
16602    ("sigmaf") ("varsigma"."&sigmaf;")
16603    ("sigma")
16604    ("tau")
16605    ("upsilon")
16606    ("phi")
16607    ("chi")
16608    ("psi")
16609    ("omega")
16610    ("thetasym") ("vartheta"."&thetasym;")
16611    ("upsih")
16612    ("piv")
16613    ("bull") ("bullet"."&bull;")
16614    ("hellip") ("dots"."&hellip;")
16615    ("prime")
16616    ("Prime")
16617    ("oline")
16618    ("frasl")
16619    ("weierp")
16620    ("image")
16621    ("real")
16622    ("trade")
16623    ("alefsym")
16624    ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
16625    ("uarr") ("uparrow"."&uarr;")
16626    ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
16627    ("darr")("downarrow"."&darr;")
16628    ("harr") ("leftrightarrow"."&harr;")
16629    ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
16630    ("lArr") ("Leftarrow"."&lArr;")
16631    ("uArr") ("Uparrow"."&uArr;")
16632    ("rArr") ("Rightarrow"."&rArr;")
16633    ("dArr") ("Downarrow"."&dArr;")
16634    ("hArr") ("Leftrightarrow"."&hArr;")
16635    ("forall")
16636    ("part") ("partial"."&part;")
16637    ("exist") ("exists"."&exist;")
16638    ("empty") ("emptyset"."&empty;")
16639    ("nabla")
16640    ("isin") ("in"."&isin;")
16641    ("notin")
16642    ("ni")
16643    ("prod")
16644    ("sum")
16645    ("minus")
16646    ("lowast") ("ast"."&lowast;")
16647    ("radic")
16648    ("prop") ("proptp"."&prop;")
16649    ("infin") ("infty"."&infin;")
16650    ("ang") ("angle"."&ang;")
16651    ("and") ("vee"."&and;")
16652    ("or") ("wedge"."&or;")
16653    ("cap")
16654    ("cup")
16655    ("int")
16656    ("there4")
16657    ("sim")
16658    ("cong") ("simeq"."&cong;")
16659    ("asymp")("approx"."&asymp;")
16660    ("ne") ("neq"."&ne;")
16661    ("equiv")
16662    ("le")
16663    ("ge")
16664    ("sub") ("subset"."&sub;")
16665    ("sup") ("supset"."&sup;")
16666    ("nsub")
16667    ("sube")
16668    ("supe")
16669    ("oplus")
16670    ("otimes")
16671    ("perp")
16672    ("sdot") ("cdot"."&sdot;")
16673    ("lceil")
16674    ("rceil")
16675    ("lfloor")
16676    ("rfloor")
16677    ("lang")
16678    ("rang")
16679    ("loz") ("Diamond"."&loz;")
16680    ("spades") ("spadesuit"."&spades;")
16681    ("clubs") ("clubsuit"."&clubs;")
16682    ("hearts") ("diamondsuit"."&hearts;")
16683    ("diams") ("diamondsuit"."&diams;")
16684    ("quot")
16685    ("amp")
16686    ("lt")
16687    ("gt")
16688    ("OElig")
16689    ("oelig")
16690    ("Scaron")
16691    ("scaron")
16692    ("Yuml")
16693    ("circ")
16694    ("tilde")
16695    ("ensp")
16696    ("emsp")
16697    ("thinsp")
16698    ("zwnj")
16699    ("zwj")
16700    ("lrm")
16701    ("rlm")
16702    ("ndash")
16703    ("mdash")
16704    ("lsquo")
16705    ("rsquo")
16706    ("sbquo")
16707    ("ldquo")
16708    ("rdquo")
16709    ("bdquo")
16710    ("dagger")
16711    ("Dagger")
16712    ("permil")
16713    ("lsaquo")
16714    ("rsaquo")
16715    ("euro")
16716
16717    ("arccos"."arccos")
16718    ("arcsin"."arcsin")
16719    ("arctan"."arctan")
16720    ("arg"."arg")
16721    ("cos"."cos")
16722    ("cosh"."cosh")
16723    ("cot"."cot")
16724    ("coth"."coth")
16725    ("csc"."csc")
16726    ("deg"."deg")
16727    ("det"."det")
16728    ("dim"."dim")
16729    ("exp"."exp")
16730    ("gcd"."gcd")
16731    ("hom"."hom")
16732    ("inf"."inf")
16733    ("ker"."ker")
16734    ("lg"."lg")
16735    ("lim"."lim")
16736    ("liminf"."liminf")
16737    ("limsup"."limsup")
16738    ("ln"."ln")
16739    ("log"."log")
16740    ("max"."max")
16741    ("min"."min")
16742    ("Pr"."Pr")
16743    ("sec"."sec")
16744    ("sin"."sin")
16745    ("sinh"."sinh")
16746    ("sup"."sup")
16747    ("tan"."tan")
16748    ("tanh"."tanh")
16749    )
16750  "Entities for TeX->HTML translation.
16751Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
16752\"&ent;\".  An entry can also be a dotted pair like (\"ent\".\"&other;\").
16753In that case, \"\\ent\" will be translated to \"&other;\".
16754The list contains HTML entities for Latin-1, Greek and other symbols.
16755It is supplemented by a number of commonly used TeX macros with appropriate
16756translations.  There is currently no way for users to extend this.")
16757
16758;;; General functions for all backends
16759
16760(defun org-cleaned-string-for-export (string &rest parameters)
16761  "Cleanup a buffer substring so that links can be created safely."
16762  (interactive)
16763  (let* ((re-radio (and org-target-link-regexp
16764			(concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
16765	 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
16766	 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
16767	 (re-archive (concat ":" org-archive-tag ":"))
16768	 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
16769	 (htmlp (memq :for-html parameters))
16770	 (outline-regexp "\\*+")
16771	 rtn)
16772    (save-excursion
16773      (set-buffer (get-buffer-create " org-mode-tmp"))
16774      (erase-buffer)
16775      (insert string)
16776      (let ((org-inhibit-startup t)) (org-mode))
16777      (untabify (point-min) (point-max))
16778
16779      ;; Get rid of archived trees
16780      (when (not (eq org-export-with-archived-trees t))
16781	(goto-char (point-min))
16782	(while (re-search-forward re-archive nil t)
16783	  (if (not (org-on-heading-p))
16784	      (org-end-of-subtree t)
16785	    (beginning-of-line 1)
16786	    (delete-region
16787	     (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
16788	     (org-end-of-subtree t)))))
16789
16790      ;; Protect stuff from HTML processing
16791      (goto-char (point-min))
16792      (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
16793	(add-text-properties (match-beginning 0) (match-end 0)
16794			     '(org-protected t)))
16795      (when htmlp
16796	(goto-char (point-min))
16797	(while (re-search-forward "^#\\+HTML:[ \t]*\\(.*\\)" nil t)
16798	  (replace-match "\\1" t)
16799	  (add-text-properties
16800	   (point-at-bol) (min (1+ (point-at-eol)) (point-max))
16801	   '(org-protected t))))
16802      (goto-char (point-min))
16803      (while (re-search-forward
16804	      "^#\\+BEGIN_HTML\\>.*\\(\n.*\\)*?\n#\\+END_HTML\\>.*\n?" nil t)
16805	(if htmlp
16806	    (add-text-properties (match-beginning 1) (1+ (match-end 1))
16807				 '(org-protected t))
16808	  (delete-region (match-beginning 0) (match-end 0))))
16809      (goto-char (point-min))
16810      (while (re-search-forward re-quote nil t)
16811	(goto-char (match-beginning 0))
16812	(end-of-line 1)
16813	(add-text-properties (point) (org-end-of-subtree t)
16814			     '(org-protected t)))
16815
16816      ;; Find targets in comments and move them out of comments,
16817      ;; but mark them as targets that should be invisible
16818      (goto-char (point-min))
16819      (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
16820	(replace-match "\\1(INVISIBLE)"))
16821
16822      ;; Remove comments
16823      (goto-char (point-min))
16824      (while (re-search-forward "^#.*\n?" nil t)
16825	(replace-match ""))
16826
16827      ;; Find matches for radio targets and turn them into internal links
16828      (goto-char (point-min))
16829      (when re-radio
16830	(while (re-search-forward re-radio nil t)
16831	  (org-if-unprotected
16832	   (replace-match "\\1[[\\2]]"))))
16833
16834      ;; Find all links that contain a newline and put them into a single line
16835      (goto-char (point-min))
16836      (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
16837	(org-if-unprotected
16838	 (replace-match "\\1 \\3")
16839	 (goto-char (match-beginning 0))))
16840
16841      ;; Convert LaTeX fragments to images
16842      (when (memq :LaTeX-fragments parameters)
16843	(org-format-latex
16844	 (concat "ltxpng/" (file-name-sans-extension
16845			    (file-name-nondirectory
16846			     org-current-export-file)))
16847	 org-current-export-dir nil "Creating LaTeX image %s"))
16848      (message "Exporting...")
16849
16850      ;; Normalize links: Convert angle and plain links into bracket links
16851      ;; Expand link abbreviations
16852      (goto-char (point-min))
16853      (while (re-search-forward re-plain-link nil t)
16854	(org-if-unprotected
16855	 (replace-match
16856	  (concat
16857	   (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
16858	  t t)))
16859      (goto-char (point-min))
16860      (while (re-search-forward re-angle-link nil t)
16861	(org-if-unprotected
16862	 (replace-match
16863	  (concat
16864	   (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
16865	  t t)))
16866      (goto-char (point-min))
16867      (while (re-search-forward org-bracket-link-regexp nil t)
16868	(org-if-unprotected
16869	 (replace-match
16870	  (concat "[[" (save-match-data
16871			 (org-link-expand-abbrev (match-string 1)))
16872		  "]"
16873		  (if (match-end 3)
16874		      (match-string 2)
16875		    (concat "[" (match-string 1) "]"))
16876		  "]")
16877	  t t)))
16878
16879      ;; Find multiline emphasis and put them into single line
16880      (when (memq :emph-multiline parameters)
16881	(goto-char (point-min))
16882	(while (re-search-forward org-emph-re nil t)
16883	  (org-if-unprotected
16884	   (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\  t)
16885	   (goto-char (1- (match-end 0))))))
16886
16887      (setq rtn (buffer-string)))
16888    (kill-buffer " org-mode-tmp")
16889    rtn))
16890
16891(defun org-solidify-link-text (s &optional alist)
16892  "Take link text and make a safe target out of it."
16893  (save-match-data
16894    (let* ((rtn
16895	    (mapconcat
16896	     'identity
16897	     (org-split-string s "[ \t\r\n]+") "--"))
16898	   (a (assoc rtn alist)))
16899      (or (cdr a) rtn))))
16900
16901;; Variable holding the vector with section numbers
16902(defvar org-section-numbers (make-vector org-level-max 0))
16903
16904(defun org-init-section-numbers ()
16905  "Initialize the vector for the section numbers."
16906  (let* ((level  -1)
16907	 (numbers (nreverse (org-split-string "" "\\.")))
16908	 (depth (1- (length org-section-numbers)))
16909	 (i depth) number-string)
16910    (while (>= i 0)
16911      (if (> i level)
16912	  (aset org-section-numbers i 0)
16913	(setq number-string (or (car numbers) "0"))
16914	(if (string-match "\\`[A-Z]\\'" number-string)
16915	    (aset org-section-numbers i
16916		  (- (string-to-char number-string) ?A -1))
16917	    (aset org-section-numbers i (string-to-number number-string)))
16918	(pop numbers))
16919      (setq i (1- i)))))
16920
16921(defun org-section-number (&optional level)
16922  "Return a string with the current section number.
16923When LEVEL is non-nil, increase section numbers on that level."
16924  (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
16925    (when level
16926      (when (> level -1)
16927	(aset org-section-numbers
16928	      level (1+ (aref org-section-numbers level))))
16929      (setq idx (1+ level))
16930      (while (<= idx depth)
16931	(if (not (= idx 1))
16932	    (aset org-section-numbers idx 0))
16933	(setq idx (1+ idx))))
16934    (setq idx 0)
16935    (while (<= idx depth)
16936      (setq n (aref org-section-numbers idx))
16937      (setq string (concat string (if (not (string= string "")) "." "")
16938			   (int-to-string n)))
16939      (setq idx (1+ idx)))
16940    (save-match-data
16941      (if (string-match "\\`\\([@0]\\.\\)+" string)
16942	  (setq string (replace-match "" t nil string)))
16943      (if (string-match "\\(\\.0\\)+\\'" string)
16944	  (setq string (replace-match "" t nil string))))
16945    string))
16946
16947;;; ASCII export
16948
16949(defvar org-last-level nil) ; dynamically scoped variable
16950(defvar org-levels-open nil) ; dynamically scoped parameter
16951(defvar org-ascii-current-indentation nil) ; For communication
16952
16953(defun org-export-as-ascii (arg)
16954  "Export the outline as a pretty ASCII file.
16955If there is an active region, export only the region.
16956The prefix ARG specifies how many levels of the outline should become
16957underlined headlines.  The default is 3."
16958  (interactive "P")
16959  (setq-default org-todo-line-regexp org-todo-line-regexp)
16960  (let* ((opt-plist (org-combine-plists (org-default-export-plist)
16961					(org-infile-export-plist)))
16962	 (region
16963	  (buffer-substring
16964	   (if (org-region-active-p) (region-beginning) (point-min))
16965	   (if (org-region-active-p) (region-end) (point-max))))
16966	 (custom-times org-display-custom-times)
16967	 (lines (org-export-find-first-heading-line
16968		 (org-skip-comments
16969		  (org-split-string
16970		   (org-cleaned-string-for-export region)
16971		   "[\r\n]"))))
16972	 (org-ascii-current-indentation '(0 . 0))
16973	 (level 0) line txt
16974	 (umax nil)
16975	 (umax-toc nil)
16976	 (case-fold-search nil)
16977         (filename (concat (file-name-as-directory
16978			    (org-export-directory :ascii opt-plist))
16979			   (file-name-sans-extension
16980			    (file-name-nondirectory buffer-file-name))
16981			   ".txt"))
16982	 (buffer (find-file-noselect filename))
16983	 (org-levels-open (make-vector org-level-max nil))
16984	 (odd org-odd-levels-only)
16985	 (date  (format-time-string "%Y/%m/%d" (current-time)))
16986	 (time  (format-time-string "%X" (org-current-time)))
16987	 (author      (plist-get opt-plist :author))
16988	 (title       (or (plist-get opt-plist :title)
16989			  (file-name-sans-extension
16990			   (file-name-nondirectory buffer-file-name))))
16991	 (email       (plist-get opt-plist :email))
16992	 (language    (plist-get opt-plist :language))
16993	 (quote-re0   (concat "^[ \t]*" org-quote-string "\\>"))
16994;	 (quote-re    (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
16995	 (text        nil)
16996	 (todo nil)
16997	 (lang-words nil))
16998
16999    (setq org-last-level 1)
17000    (org-init-section-numbers)
17001
17002    (find-file-noselect filename)
17003
17004    (setq lang-words (or (assoc language org-export-language-setup)
17005			 (assoc "en" org-export-language-setup)))
17006    (switch-to-buffer-other-window buffer)
17007    (erase-buffer)
17008    (fundamental-mode)
17009    ;; create local variables for all options, to make sure all called
17010    ;; functions get the correct information
17011    (mapcar (lambda (x)
17012	      (set (make-local-variable (cdr x))
17013		   (plist-get opt-plist (car x))))
17014	    org-export-plist-vars)
17015    (org-set-local 'org-odd-levels-only odd)
17016    (setq umax (if arg (prefix-numeric-value arg)
17017		 org-export-headline-levels))
17018    (setq umax-toc (if (integerp org-export-with-toc)
17019		       (min org-export-with-toc umax)
17020		     umax))
17021
17022    ;; File header
17023    (if title (org-insert-centered title ?=))
17024    (insert "\n")
17025    (if (or author email)
17026	(insert (concat (nth 1 lang-words) ": " (or author "")
17027			(if email (concat " <" email ">") "")
17028			"\n")))
17029    (if (and date time)
17030	(insert (concat (nth 2 lang-words) ": " date " " time "\n")))
17031    (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
17032
17033    (insert "\n\n")
17034
17035    (if org-export-with-toc
17036	(progn
17037	  (insert (nth 3 lang-words) "\n"
17038		  (make-string (length (nth 3 lang-words)) ?=) "\n")
17039	  (mapcar '(lambda (line)
17040		     (if (string-match org-todo-line-regexp
17041				       line)
17042			 ;; This is a headline
17043			 (progn
17044			   (setq level (- (match-end 1) (match-beginning 1))
17045				 level (org-tr-level level)
17046				 txt (match-string 3 line)
17047				 todo
17048				 (or (and org-export-mark-todo-in-toc
17049					  (match-beginning 2)
17050					  (not (equal (match-string 2 line)
17051						      org-done-string)))
17052					; TODO, not DONE
17053				     (and org-export-mark-todo-in-toc
17054					  (= level umax-toc)
17055					  (org-search-todo-below
17056					   line lines level))))
17057			   (setq txt (org-html-expand-for-ascii txt))
17058
17059			   (if (and (memq org-export-with-tags '(not-in-toc nil))
17060				    (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
17061			       (setq txt (replace-match "" t t txt)))
17062			   (if (string-match quote-re0 txt)
17063			       (setq txt (replace-match "" t t txt)))
17064
17065			   (if org-export-with-section-numbers
17066			       (setq txt (concat (org-section-number level)
17067						 " " txt)))
17068			   (if (<= level umax-toc)
17069			       (progn
17070				 (insert
17071				  (make-string (* (1- level) 4) ?\ )
17072				  (format (if todo "%s (*)\n" "%s\n") txt))
17073				 (setq org-last-level level))
17074			     ))))
17075		  lines)))
17076
17077    (org-init-section-numbers)
17078    (while (setq line (pop lines))
17079      ;; Remove the quoted HTML tags.
17080      (setq line (org-html-expand-for-ascii line))
17081      ;; Remove targets
17082      (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
17083	(setq line (replace-match "" t t line)))
17084      ;; Replace internal links
17085      (while (string-match org-bracket-link-regexp line)
17086	(setq line (replace-match
17087		    (if (match-end 3) "[\\3]" "[\\1]")
17088		    t nil line)))
17089      (when custom-times
17090	(setq line (org-translate-time line)))
17091      (cond
17092       ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
17093	;; a Headline
17094	(setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
17095	      txt (match-string 2 line))
17096	(org-ascii-level-start level txt umax lines))
17097       (t
17098	(insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
17099    (normal-mode)
17100    (save-buffer)
17101    ;; remove display and invisible chars
17102    (let (beg end)
17103      (goto-char (point-min))
17104      (while (setq beg (next-single-property-change (point) 'display))
17105	(setq end (next-single-property-change beg 'display))
17106	(delete-region beg end)
17107	(goto-char beg)
17108	(insert "=>"))
17109      (goto-char (point-min))
17110      (while (setq beg (next-single-property-change (point) 'org-cwidth))
17111	(setq end (next-single-property-change beg 'org-cwidth))
17112	(delete-region beg end)
17113	(goto-char beg)))
17114    (goto-char (point-min))))
17115
17116(defun org-search-todo-below (line lines level)
17117  "Search the subtree below LINE for any TODO entries."
17118  (let ((rest (cdr (memq line lines)))
17119	(re org-todo-line-regexp)
17120	line lv todo)
17121    (catch 'exit
17122      (while (setq line (pop rest))
17123	(if (string-match re line)
17124	    (progn
17125	      (setq lv (- (match-end 1) (match-beginning 1))
17126		    todo (and (match-beginning 2)
17127			      (not (equal (match-string 2 line)
17128					  org-done-string))))
17129					; TODO, not DONE
17130	      (if (<= lv level) (throw 'exit nil))
17131	      (if todo (throw 'exit t))))))))
17132
17133(defun org-html-expand-for-ascii (line)
17134  "Handle quoted HTML for ASCII export."
17135  (if org-export-html-expand
17136      (while (string-match "@<[^<>\n]*>" line)
17137	;; We just remove the tags for now.
17138	(setq line (replace-match "" nil nil line))))
17139  line)
17140
17141(defun org-insert-centered (s &optional underline)
17142  "Insert the string S centered and underline it with character UNDERLINE."
17143  (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
17144    (insert (make-string ind ?\ ) s "\n")
17145    (if underline
17146	(insert (make-string ind ?\ )
17147		(make-string (string-width s) underline)
17148		"\n"))))
17149
17150(defun org-ascii-level-start (level title umax &optional lines)
17151  "Insert a new level in ASCII export."
17152  (let (char (n (- level umax 1)) (ind 0))
17153    (if (> level umax)
17154	(progn
17155	  (insert (make-string (* 2 n) ?\ )
17156		  (char-to-string (nth (% n (length org-export-ascii-bullets))
17157				       org-export-ascii-bullets))
17158		  " " title "\n")
17159	  ;; find the indentation of the next non-empty line
17160	  (catch 'stop
17161	    (while lines
17162	      (if (string-match "^\\*" (car lines)) (throw 'stop nil))
17163	      (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
17164		  (throw 'stop (setq ind (org-get-indentation (car lines)))))
17165	      (pop lines)))
17166	  (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
17167      (if (or (not (equal (char-before) ?\n))
17168	      (not (equal (char-before (1- (point))) ?\n)))
17169	  (insert "\n"))
17170      (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
17171      (unless org-export-with-tags
17172	(if (string-match "[ \t]+\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
17173	    (setq title (replace-match "" t t title))))
17174      (if org-export-with-section-numbers
17175	  (setq title (concat (org-section-number level) " " title)))
17176      (insert title "\n" (make-string (string-width title) char) "\n")
17177      (setq org-ascii-current-indentation '(0 . 0)))))
17178
17179(defun org-export-visible (type arg)
17180  "Create a copy of the visible part of the current buffer, and export it.
17181The copy is created in a temporary buffer and removed after use.
17182TYPE is the final key (as a string) that also select the export command in
17183the `C-c C-e' export dispatcher.
17184As a special case, if the you type SPC at the prompt, the temporary
17185org-mode file will not be removed but presented to you so that you can
17186continue to use it.  The prefix arg ARG is passed through to the exporting
17187command."
17188  (interactive
17189   (list (progn
17190	   (message "Export visible: [a]SCII  [h]tml  [b]rowse HTML  [x]OXO  [ ]keep buffer")
17191	   (read-char-exclusive))
17192	 current-prefix-arg))
17193  (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
17194      (error "Invalid export key"))
17195  (let* ((binding (cdr (assoc type
17196			      '((?a . org-export-as-ascii)
17197				(?\C-a . org-export-as-ascii)
17198				(?b . org-export-as-html-and-open)
17199				(?\C-b . org-export-as-html-and-open)
17200				(?h . org-export-as-html)
17201				(?x . org-export-as-xoxo)))))
17202	 (keepp (equal type ?\ ))
17203	 (file buffer-file-name)
17204	 (buffer (get-buffer-create "*Org Export Visible*"))
17205	 s e)
17206    (with-current-buffer buffer (erase-buffer))
17207    (save-excursion
17208      (setq s (goto-char (point-min)))
17209      (while (not (= (point) (point-max)))
17210	(goto-char (org-find-invisible))
17211	(append-to-buffer buffer s (point))
17212	(setq s (goto-char (org-find-visible))))
17213      (goto-char (point-min))
17214      (unless keepp
17215	;; Copy all comment lines to the end, to make sure #+ settings are
17216	;; still available for the second export step.  Kind of a hack, but
17217	;; does do the trick.
17218	(if (looking-at "#[^\r\n]*")
17219	    (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
17220	(while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
17221	  (append-to-buffer buffer (1+ (match-beginning 0))
17222			    (min (point-max) (1+ (match-end 0))))))
17223      (set-buffer buffer)
17224      (let ((buffer-file-name file)
17225	    (org-inhibit-startup t))
17226	(org-mode)
17227	(show-all)
17228	(unless keepp (funcall binding arg))))
17229    (if (not keepp)
17230	(kill-buffer buffer)
17231      (switch-to-buffer-other-window buffer)
17232      (goto-char (point-min)))))
17233
17234(defun org-find-visible ()
17235  (let ((s (point)))
17236    (while (and (not (= (point-max) (setq s (next-overlay-change s))))
17237		(get-char-property s 'invisible)))
17238    s))
17239(defun org-find-invisible ()
17240  (let ((s (point)))
17241    (while (and (not (= (point-max) (setq s (next-overlay-change s))))
17242		(not (get-char-property s 'invisible))))
17243    s))
17244
17245;;; HTML export
17246
17247(defun org-get-current-options ()
17248  "Return a string with current options as keyword options.
17249Does include HTML export options as well as TODO and CATEGORY stuff."
17250  (format
17251   "#+TITLE:     %s
17252#+AUTHOR:    %s
17253#+EMAIL:     %s
17254#+LANGUAGE:  %s
17255#+TEXT:      Some descriptive text to be emitted.  Several lines OK.
17256#+OPTIONS:   H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
17257#+CATEGORY:  %s
17258#+SEQ_TODO:  %s
17259#+TYP_TODO:  %s
17260#+STARTUP:   %s %s %s %s %s
17261#+TAGS:      %s
17262#+ARCHIVE:   %s
17263#+LINK:      %s
17264"
17265   (buffer-name) (user-full-name) user-mail-address org-export-default-language
17266   org-export-headline-levels
17267   org-export-with-section-numbers
17268   org-export-with-toc
17269   org-export-preserve-breaks
17270   org-export-html-expand
17271   org-export-with-fixed-width
17272   org-export-with-tables
17273   org-export-with-sub-superscripts
17274   org-export-with-emphasize
17275   org-export-with-TeX-macros
17276   org-export-with-LaTeX-fragments
17277   (file-name-nondirectory buffer-file-name)
17278   (if (equal org-todo-interpretation 'sequence)
17279       (mapconcat 'identity org-todo-keywords " ")
17280     "TODO FEEDBACK VERIFY DONE")
17281   (if (equal org-todo-interpretation 'type)
17282       (mapconcat 'identity org-todo-keywords " ")
17283     "Me Jason Marie DONE")
17284   (cdr (assoc org-startup-folded
17285	       '((nil . "showall") (t . "overview") (content . "content"))))
17286   (if org-odd-levels-only "odd" "oddeven")
17287   (if org-hide-leading-stars "hidestars" "showstars")
17288   (if org-startup-align-all-tables "align" "noalign")
17289   (cond ((eq t org-log-done) "logdone")
17290	 ((not org-log-done) "nologging")
17291	 ((listp org-log-done)
17292	  (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
17293		     org-log-done " ")))
17294   (or (mapconcat (lambda (x)
17295		    (cond
17296		     ((equal '(:startgroup) x) "{")
17297		     ((equal '(:endgroup) x) "}")
17298		     ((cdr x) (format "%s(%c)" (car x) (cdr x)))
17299		     (t (car x))))
17300		  (or org-tag-alist (org-get-buffer-tags)) " ") "")
17301   org-archive-location
17302   "org file:~/org/%s.org"
17303   ))
17304
17305(defun org-insert-export-options-template ()
17306  "Insert into the buffer a template with information for exporting."
17307  (interactive)
17308  (if (not (bolp)) (newline))
17309  (let ((s (org-get-current-options)))
17310    (and (string-match "#\\+CATEGORY" s)
17311	 (setq s (substring s 0 (match-beginning 0))))
17312    (insert s)))
17313
17314(defun org-toggle-fixed-width-section (arg)
17315  "Toggle the fixed-width export.
17316If there is no active region, the QUOTE keyword at the current headline is
17317inserted or removed.  When present, it causes the text between this headline
17318and the next to be exported as fixed-width text, and unmodified.
17319If there is an active region, this command adds or removes a colon as the
17320first character of this line.  If the first character of a line is a colon,
17321this line is also exported in fixed-width font."
17322  (interactive "P")
17323  (let* ((cc 0)
17324	 (regionp (org-region-active-p))
17325	 (beg (if regionp (region-beginning) (point)))
17326	 (end (if regionp (region-end)))
17327	 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17328	 (re "[ \t]*\\(:\\)")
17329	 off)
17330    (if regionp
17331	(save-excursion
17332	  (goto-char beg)
17333	  (setq cc (current-column))
17334	  (beginning-of-line 1)
17335	  (setq off (looking-at re))
17336	  (while (> nlines 0)
17337	    (setq nlines (1- nlines))
17338	    (beginning-of-line 1)
17339	    (cond
17340	     (arg
17341	      (move-to-column cc t)
17342	      (insert ":\n")
17343	      (forward-line -1))
17344	     ((and off (looking-at re))
17345	      (replace-match "" t t nil 1))
17346	     ((not off) (move-to-column cc t) (insert ":")))
17347	    (forward-line 1)))
17348      (save-excursion
17349	(org-back-to-heading)
17350	(if (looking-at (concat outline-regexp
17351				"\\( +\\<" org-quote-string "\\>\\)"))
17352	    (replace-match "" t t nil 1)
17353	  (if (looking-at outline-regexp)
17354	      (progn
17355		(goto-char (match-end 0))
17356		(insert " " org-quote-string))))))))
17357
17358(defun org-export-as-html-and-open (arg)
17359  "Export the outline as HTML and immediately open it with a browser.
17360If there is an active region, export only the region.
17361The prefix ARG specifies how many levels of the outline should become
17362headlines.  The default is 3.  Lower levels will become bulleted lists."
17363  (interactive "P")
17364  (org-export-as-html arg 'hidden)
17365  (org-open-file buffer-file-name))
17366
17367(defun org-export-as-html-batch ()
17368  "Call `org-export-as-html', may be used in batch processing as
17369emacs 	--batch
17370	--load=$HOME/lib/emacs/org.el
17371	--eval \"(setq org-export-headline-levels 2)\"
17372	--visit=MyFile --funcall org-export-as-html-batch"
17373  (org-export-as-html org-export-headline-levels 'hidden))
17374
17375(defun org-export-as-html (arg &optional hidden ext-plist)
17376  "Export the outline as a pretty HTML file.
17377If there is an active region, export only the region.
17378The prefix ARG specifies how many levels of the outline should become
17379headlines.  The default is 3.  Lower levels will become bulleted lists.
17380When HIDDEN is non-nil, don't display the HTML buffer.
17381EXT-PLIST is a property list with external parameters overriding
17382org-mode's default settings, but still inferior to file-local settings."
17383  (interactive "P")
17384  (message "Exporting...")
17385  (setq-default org-todo-line-regexp org-todo-line-regexp)
17386  (setq-default org-deadline-line-regexp org-deadline-line-regexp)
17387  (setq-default org-done-string org-done-string)
17388  (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
17389  (let* ((opt-plist (org-combine-plists (org-default-export-plist)
17390					ext-plist
17391					(org-infile-export-plist)))
17392
17393	 (style (plist-get opt-plist :style))
17394	 (link-validate (plist-get opt-plist :link-validation-function))
17395	 valid
17396	 (odd org-odd-levels-only)
17397	 (region-p (org-region-active-p))
17398         (region
17399          (buffer-substring
17400           (if region-p (region-beginning) (point-min))
17401           (if region-p (region-end) (point-max))))
17402	 ;; The following two are dynamically scoped into other
17403	 ;; routines below.
17404	 (org-current-export-dir (org-export-directory :html opt-plist))
17405	 (org-current-export-file buffer-file-name)
17406         (all_lines
17407          (org-skip-comments (org-split-string
17408			      (org-cleaned-string-for-export
17409			       region :emph-multiline :for-html
17410			       (if (plist-get opt-plist :LaTeX-fragments)
17411				   :LaTeX-fragments))
17412			      "[\r\n]")))
17413         (lines (org-export-find-first-heading-line all_lines))
17414         (level 0) (line "") (origline "") txt todo
17415         (umax nil)
17416         (umax-toc nil)
17417         (filename (concat (file-name-as-directory
17418			    (org-export-directory :html opt-plist))
17419			   (file-name-sans-extension
17420			    (file-name-nondirectory buffer-file-name))
17421			   ".html"))
17422	 (current-dir (file-name-directory buffer-file-name))
17423         (buffer (find-file-noselect filename))
17424         (org-levels-open (make-vector org-level-max nil))
17425	 (date (format-time-string "%Y/%m/%d" (current-time)))
17426	 (time  (format-time-string "%X" (org-current-time)))
17427         (author      (plist-get opt-plist :author))
17428	 (title       (or (plist-get opt-plist :title)
17429			  (file-name-sans-extension
17430			   (file-name-nondirectory buffer-file-name))))
17431	 (quote-re0   (concat "^[ \t]*" org-quote-string "\\>"))
17432	 (quote-re    (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
17433	 (inquote     nil)
17434	 (infixed     nil)
17435	 (in-local-list nil)
17436	 (local-list-num nil)
17437	 (local-list-indent nil)
17438	 (llt org-plain-list-ordered-item-terminator)
17439	 (email       (plist-get opt-plist :email))
17440         (language    (plist-get opt-plist :language))
17441	 (text        (plist-get opt-plist :text))
17442	 (lang-words  nil)
17443	 (target-alist nil) tg
17444	 (head-count  0) cnt
17445	 (start       0)
17446	 (coding-system (and (boundp 'buffer-file-coding-system)
17447			     buffer-file-coding-system))
17448	 (coding-system-for-write coding-system)
17449	 (save-buffer-coding-system coding-system)
17450	 (charset (and coding-system
17451		       (fboundp 'coding-system-get)
17452		       (coding-system-get coding-system 'mime-charset)))
17453	 table-open type
17454	 table-buffer table-orig-buffer
17455	 ind start-is-num starter
17456	 rpl path desc descp desc1 desc2 link
17457	 )
17458    (message "Exporting...")
17459
17460    (setq org-last-level 1)
17461    (org-init-section-numbers)
17462
17463    ;; Get the language-dependent settings
17464    (setq lang-words (or (assoc language org-export-language-setup)
17465                         (assoc "en" org-export-language-setup)))
17466
17467    ;; Switch to the output buffer
17468    (if (or hidden t)
17469        (set-buffer buffer)
17470      (switch-to-buffer-other-window buffer))
17471    (erase-buffer)
17472    (fundamental-mode)
17473    (let ((case-fold-search nil)
17474	  (org-odd-levels-only odd))
17475      ;; create local variables for all options, to make sure all called
17476      ;; functions get the correct information
17477      (mapcar (lambda (x)
17478		(set (make-local-variable (cdr x))
17479		     (plist-get opt-plist (car x))))
17480	      org-export-plist-vars)
17481      (setq umax (if arg (prefix-numeric-value arg)
17482                   org-export-headline-levels))
17483      (setq umax-toc (if (integerp org-export-with-toc)
17484			 (min org-export-with-toc umax)
17485		       umax))
17486
17487      ;; File header
17488      (insert (format
17489               "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
17490               \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
17491<html xmlns=\"http://www.w3.org/1999/xhtml\"
17492lang=\"%s\" xml:lang=\"%s\">
17493<head>
17494<title>%s</title>
17495<meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
17496<meta name=\"generator\" content=\"Org-mode\"/>
17497<meta name=\"generated\" content=\"%s %s\"/>
17498<meta name=\"author\" content=\"%s\"/>
17499%s
17500</head><body>
17501"
17502	       language language (org-html-expand title) (or charset "iso-8859-1")
17503	       date time author style))
17504
17505
17506      (insert (or (plist-get opt-plist :preamble) ""))
17507
17508      (when (plist-get opt-plist :auto-preamble)
17509	(if title     (insert (format org-export-html-title-format
17510				      (org-html-expand title))))
17511	(if text      (insert "<p>\n" (org-html-expand text) "</p>")))
17512
17513      (if org-export-with-toc
17514	  (progn
17515	    (insert (format "<h%d>%s</h%d>\n"
17516			    org-export-html-toplevel-hlevel
17517			    (nth 3 lang-words)
17518			    org-export-html-toplevel-hlevel))
17519	    (insert "<ul>\n<li>")
17520	    (setq lines
17521	    (mapcar '(lambda (line)
17522		       (if (string-match org-todo-line-regexp line)
17523			   ;; This is a headline
17524			   (progn
17525			     (setq level (- (match-end 1) (match-beginning 1))
17526				   level (org-tr-level level)
17527				   txt (save-match-data
17528					 (org-html-expand
17529					  (org-export-cleanup-toc-line
17530					   (match-string 3 line))))
17531				   todo
17532				   (or (and org-export-mark-todo-in-toc
17533					    (match-beginning 2)
17534					    (not (equal (match-string 2 line)
17535							org-done-string)))
17536					; TODO, not DONE
17537				       (and org-export-mark-todo-in-toc
17538					    (= level umax-toc)
17539					    (org-search-todo-below
17540					     line lines level))))
17541			     (if (and (memq org-export-with-tags '(not-in-toc nil))
17542				      (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
17543				 (setq txt (replace-match "" t t txt)))
17544			     (if (string-match quote-re0 txt)
17545				 (setq txt (replace-match "" t t txt)))
17546			     (if org-export-with-section-numbers
17547				 (setq txt (concat (org-section-number level)
17548						   " " txt)))
17549			     (if (<= level umax-toc)
17550				 (progn
17551				   (setq head-count (+ head-count 1))
17552				   (if (> level org-last-level)
17553				       (progn
17554					 (setq cnt (- level org-last-level))
17555					 (while (>= (setq cnt (1- cnt)) 0)
17556					   (insert "\n<ul>\n<li>"))
17557					 (insert "\n")))
17558				   (if (< level org-last-level)
17559				       (progn
17560					 (setq cnt (- org-last-level level))
17561					 (while (>= (setq cnt (1- cnt)) 0)
17562					   (insert "</li>\n</ul>"))
17563					 (insert "\n")))
17564				   ;; Check for targets
17565				   (while (string-match org-target-regexp line)
17566				     (setq tg (match-string 1 line)
17567					   line (replace-match
17568						 (concat "@<span class=\"target\">" tg "@</span> ")
17569						 t t line))
17570				     (push (cons (org-solidify-link-text tg)
17571						 (format "sec-%d" head-count))
17572					   target-alist))
17573				   (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
17574				     (setq txt (replace-match "" t t txt)))
17575				   (insert
17576				    (format
17577				     (if todo
17578					 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
17579				       "</li>\n<li><a href=\"#sec-%d\">%s</a>")
17580				     head-count txt))
17581
17582				   (setq org-last-level level))
17583			       )))
17584		       line)
17585		    lines))
17586	    (while (> org-last-level 0)
17587	      (setq org-last-level (1- org-last-level))
17588	      (insert "</li>\n</ul>\n"))
17589	    ))
17590      (setq head-count 0)
17591      (org-init-section-numbers)
17592
17593      (while (setq line (pop lines) origline line)
17594	(catch 'nextline
17595
17596	  ;; end of quote section?
17597 	  (when (and inquote (string-match "^\\*+" line))
17598	    (insert "</pre>\n")
17599	    (setq inquote nil))
17600	  ;; inside a quote section?
17601	  (when inquote
17602	    (insert (org-html-protect line) "\n")
17603	    (throw 'nextline nil))
17604
17605	  ;; verbatim lines
17606	  (when (and org-export-with-fixed-width
17607		     (string-match "^[ \t]*:\\(.*\\)" line))
17608	    (when (not infixed)
17609	      (setq infixed t)
17610	      (insert "<pre>\n"))
17611	    (insert (org-html-protect (match-string 1 line)) "\n")
17612	    (when (and lines
17613		       (not (string-match "^[ \t]*\\(:.*\\)"
17614					  (car lines))))
17615	      (setq infixed nil)
17616	      (insert "</pre>\n"))
17617	    (throw 'nextline nil))
17618
17619	  ;; Protected HTML
17620	  (when (get-text-property 0 'org-protected line)
17621	    (insert line "\n")
17622	    (throw 'nextline nil))
17623
17624	  ;; Horizontal line
17625	  (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
17626	    (insert "\n<hr/>\n")
17627	    (throw 'nextline nil))
17628
17629	  ;; make targets to anchors
17630	  (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
17631	    (cond
17632	     ((match-end 2)
17633	      (setq line (replace-match
17634			  (concat "@<a name=\""
17635				  (org-solidify-link-text (match-string 1 line))
17636				  "\">\\nbsp@</a>")
17637			  t t line)))
17638	     ((and org-export-with-toc (equal (string-to-char line) ?*))
17639	      (setq line (replace-match
17640			  (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
17641;			  (concat "@<i>" (match-string 1 line) "@</i> ")
17642			  t t line)))
17643	     (t
17644	      (setq line (replace-match
17645			  (concat "@<a name=\""
17646				  (org-solidify-link-text (match-string 1 line))
17647				  "\" class=\"target\">" (match-string 1 line) "@</a> ")
17648			  t t line)))))
17649
17650	  (setq line (org-html-handle-time-stamps line))
17651
17652	  ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
17653	  ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
17654	  ;; Also handle sub_superscripts and checkboxes
17655	  (setq line (org-html-expand line))
17656
17657	  ;; Format the links
17658	  (setq start 0)
17659	  (while (string-match org-bracket-link-analytic-regexp line start)
17660	    (setq start (match-beginning 0))
17661	    (setq type (if (match-end 2) (match-string 2 line) "internal"))
17662	    (setq path (match-string 3 line))
17663	    (setq desc1 (if (match-end 5) (match-string 5 line))
17664		  desc2 (if (match-end 2) (concat type ":" path) path)
17665		  descp (and desc1 (not (equal desc1 desc2)))
17666		  desc (or desc1 desc2))
17667	    ;; Make an image out of the description if that is so wanted
17668	    (when (and descp (org-file-image-p desc))
17669	      (save-match-data
17670		(if (string-match "^file:" desc)
17671		    (setq desc (substring desc (match-end 0)))))
17672	      (setq desc (concat "<img src=\"" desc "\"/>")))
17673	    ;; FIXME: do we need to unescape here somewhere?
17674	    (cond
17675	     ((equal type "internal")
17676	      (setq rpl
17677		    (concat
17678		     "<a href=\"#"
17679		     (org-solidify-link-text path target-alist)
17680		     "\">" desc "</a>")))
17681	     ((member type '("http" "https")) ; FIXME: need to test this.
17682	      ;; standard URL, just check if we need to inline an image
17683	      (if (and (or (eq t org-export-html-inline-images)
17684			   (and org-export-html-inline-images (not descp)))
17685		       (org-file-image-p path))
17686		  (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
17687		(setq link (concat type ":" path))
17688		(setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
17689	     ((member type '("ftp" "mailto" "news"))
17690	      ;; standard URL
17691	      (setq link (concat type ":" path))
17692	      (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
17693	     ((string= type "file")
17694	      ;; FILE link
17695	      (let* ((filename path)
17696		     (abs-p (file-name-absolute-p filename))
17697		     thefile file-is-image-p search)
17698		(save-match-data
17699		  (if (string-match "::\\(.*\\)" filename)
17700		      (setq search (match-string 1 filename)
17701			    filename (replace-match "" t nil filename)))
17702		  (setq valid
17703			(if (functionp link-validate)
17704			    (funcall link-validate filename current-dir)
17705			  t))
17706		  (setq file-is-image-p (org-file-image-p filename))
17707		  (setq thefile (if abs-p (expand-file-name filename) filename))
17708		  (when (and org-export-html-link-org-files-as-html
17709			     (string-match "\\.org$" thefile))
17710		    (setq thefile (concat (substring thefile 0
17711						     (match-beginning 0))
17712					  ".html"))
17713		    (if (and search
17714			     ;; make sure this is can be used as target search
17715			     (not (string-match "^[0-9]*$" search))
17716			     (not (string-match "^\\*" search))
17717			     (not (string-match "^/.*/$" search)))
17718			(setq thefile (concat thefile "#"
17719					      (org-solidify-link-text
17720					       (org-link-unescape search)))))
17721		    (when (string-match "^file:" desc)
17722		      (setq desc (replace-match "" t t desc))
17723		      (if (string-match "\\.org$" desc)
17724			  (setq desc (replace-match "" t t desc))))))
17725		(setq rpl (if (and file-is-image-p
17726				   (or (eq t org-export-html-inline-images)
17727				       (and org-export-html-inline-images
17728					    (not descp))))
17729			      (concat "<img src=\"" thefile "\"/>")
17730			    (concat "<a href=\"" thefile "\">" desc "</a>")))
17731		(if (not valid) (setq rpl desc))))
17732	     ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
17733	      (setq rpl (concat "<i>&lt;" type ":"
17734				(save-match-data (org-link-unescape path))
17735				"&gt;</i>"))))
17736	    (setq line (replace-match rpl t t line)
17737		  start (+ start (length rpl))))
17738	  ;; TODO items
17739	  (if (and (string-match org-todo-line-regexp line)
17740		   (match-beginning 2))
17741	      (if (equal (match-string 2 line) org-done-string)
17742		  (setq line (replace-match
17743			      "<span class=\"done\">\\2</span>"
17744			      t nil line 2))
17745		(setq line (replace-match "<span class=\"todo\">\\2</span>"
17746					  t nil line 2))))
17747
17748	  (cond
17749	   ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
17750	    ;; This is a headline
17751	    (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
17752		  txt (match-string 2 line))
17753	    (if (string-match quote-re0 txt)
17754		(setq txt (replace-match "" t t txt)))
17755	    (if (<= level umax) (setq head-count (+ head-count 1)))
17756	    (when in-local-list
17757	      ;; Close any local lists before inserting a new header line
17758	      (while local-list-num
17759		(org-close-li)
17760		(insert (if (car local-list-num) "</ol>\n" "</ul>"))
17761		(pop local-list-num))
17762	      (setq local-list-indent nil
17763		    in-local-list nil))
17764	    (org-html-level-start level txt umax
17765				  (and org-export-with-toc (<= level umax))
17766				  head-count)
17767	    ;; QUOTES
17768	    (when (string-match quote-re line)
17769	      (insert "<pre>")
17770	      (setq inquote t)))
17771
17772	   ((and org-export-with-tables
17773		 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
17774	    (if (not table-open)
17775		;; New table starts
17776		(setq table-open t table-buffer nil table-orig-buffer nil))
17777	    ;; Accumulate lines
17778	    (setq table-buffer (cons line table-buffer)
17779		  table-orig-buffer (cons origline table-orig-buffer))
17780	    (when (or (not lines)
17781		      (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
17782					 (car lines))))
17783	      (setq table-open nil
17784		    table-buffer (nreverse table-buffer)
17785		    table-orig-buffer (nreverse table-orig-buffer))
17786	      (org-close-par-maybe)
17787	      (insert (org-format-table-html table-buffer table-orig-buffer))))
17788	   (t
17789	    ;; Normal lines
17790	    (when (string-match
17791		   (cond
17792		    ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
17793		    ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
17794		    ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
17795		    (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
17796		   line)
17797	      (setq ind (org-get-string-indentation line)
17798		    start-is-num (match-beginning 4)
17799		    starter (if (match-beginning 2)
17800				(substring (match-string 2 line) 0 -1))
17801		    line (substring line (match-beginning 5)))
17802	      (unless (string-match "[^ \t]" line)
17803		;; empty line.  Pretend indentation is large.
17804		(setq ind (1+ (or (car local-list-indent) 1))))
17805	      (while (and in-local-list
17806			  (or (and (= ind (car local-list-indent))
17807				   (not starter))
17808			      (< ind (car local-list-indent))))
17809		(org-close-li)
17810		(insert (if (car local-list-num) "</ol>\n" "</ul>"))
17811		(pop local-list-num) (pop local-list-indent)
17812		(setq in-local-list local-list-indent))
17813	      (cond
17814	       ((and starter
17815		     (or (not in-local-list)
17816			 (> ind (car local-list-indent))))
17817		;; Start new (level of ) list
17818		(org-close-par-maybe)
17819		(insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
17820		(push start-is-num local-list-num)
17821		(push ind local-list-indent)
17822		(setq in-local-list t))
17823	       (starter
17824		;; continue current list
17825		(org-close-li)
17826		(insert "<li>\n")))
17827	      (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
17828		  (setq line
17829			(replace-match
17830			 (if (equal (match-string 1 line) "X")
17831			     "<b>[X]</b>"
17832			   "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
17833			   t t line))))
17834
17835	    ;; Empty lines start a new paragraph.  If hand-formatted lists
17836	    ;; are not fully interpreted, lines starting with "-", "+", "*"
17837	    ;; also start a new paragraph.
17838	    (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
17839
17840	    ;; Check if the line break needs to be conserved
17841	    (cond
17842	     ((string-match "\\\\\\\\[ \t]*$" line)
17843	      (setq line (replace-match "<br/>" t t line)))
17844	     (org-export-preserve-breaks
17845	      (setq line (concat line "<br/>"))))
17846
17847	    (insert line "\n")))))
17848
17849      ;; Properly close all local lists and other lists
17850      (when inquote (insert "</pre>\n"))
17851      (when in-local-list
17852	;; Close any local lists before inserting a new header line
17853	(while local-list-num
17854	  (org-close-li)
17855	  (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
17856	  (pop local-list-num))
17857	(setq local-list-indent nil
17858	      in-local-list nil))
17859      (org-html-level-start 1 nil umax
17860			    (and org-export-with-toc (<= level umax))
17861			    head-count)
17862
17863      (when (plist-get opt-plist :auto-postamble)
17864	(when author
17865	  (insert "<p class=\"author\"> "
17866		  (nth 1 lang-words) ": " author "\n")
17867	  (when email
17868	    (insert "<a href=\"mailto:" email "\">&lt;"
17869		    email "&gt;</a>\n"))
17870	  (insert "</p>\n"))
17871	(when (and date time)
17872	  (insert "<p class=\"date\"> "
17873		  (nth 2 lang-words) ": "
17874		  date " " time "</p>\n")))
17875
17876      (if org-export-html-with-timestamp
17877	  (insert org-export-html-html-helper-timestamp))
17878      (insert (or (plist-get opt-plist :postamble) ""))
17879      (insert "</body>\n</html>\n")
17880      (normal-mode)
17881      ;; remove empty paragraphs and lists
17882      (goto-char (point-min))
17883      (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
17884	(replace-match ""))
17885      (goto-char (point-min))
17886      (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
17887	(replace-match ""))
17888      (save-buffer)
17889      (goto-char (point-min))
17890      (message "Exporting... done"))))
17891
17892
17893(defun org-format-table-html (lines olines)
17894  "Find out which HTML converter to use and return the HTML code."
17895  (if (string-match "^[ \t]*|" (car lines))
17896      ;; A normal org table
17897      (org-format-org-table-html lines)
17898    ;; Table made by table.el - test for spanning
17899    (let* ((hlines (delq nil (mapcar
17900			      (lambda (x)
17901				(if (string-match "^[ \t]*\\+-" x) x
17902				  nil))
17903			      lines)))
17904	   (first (car hlines))
17905	   (ll (and (string-match "\\S-+" first)
17906		    (match-string 0 first)))
17907	   (re (concat "^[ \t]*" (regexp-quote ll)))
17908	   (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
17909				       hlines))))
17910      (if (and (not spanning)
17911	       (not org-export-prefer-native-exporter-for-tables))
17912	  ;; We can use my own converter with HTML conversions
17913	  (org-format-table-table-html lines)
17914	;; Need to use the code generator in table.el, with the original text.
17915	(org-format-table-table-html-using-table-generate-source olines)))))
17916
17917(defun org-format-org-table-html (lines &optional splice)
17918  "Format a table into HTML."
17919  ;; Get rid of hlines at beginning and end
17920  (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
17921  (setq lines (nreverse lines))
17922  (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
17923  (setq lines (nreverse lines))
17924  (when org-export-table-remove-special-lines
17925    ;; Check if the table has a marking column.  If yes remove the
17926    ;; column and the special lines
17927    (setq lines (org-table-clean-before-export lines)))
17928
17929  (let ((head (and org-export-highlight-first-table-line
17930		   (delq nil (mapcar
17931			      (lambda (x) (string-match "^[ \t]*|-" x))
17932			      (cdr lines)))))
17933	(nlines 0) fnum i
17934	tbopen line fields html)
17935    (if splice (setq head nil))
17936    (unless splice (push (if head "<thead>" "<tbody>") html))
17937    (setq tbopen t)
17938    (while (setq line (pop lines))
17939      (catch 'next-line
17940	(if (string-match "^[ \t]*|-" line)
17941	    (progn
17942	      (unless splice
17943		(push (if head "</thead>" "</tbody>") html)
17944		(if lines (push "<tbody>" html) (setq tbopen nil)))
17945	      (setq head nil)   ;; head ends here, first time around
17946	      ;; ignore this line
17947	      (throw 'next-line t)))
17948	;; Break the line into fields
17949	(setq fields (org-split-string line "[ \t]*|[ \t]*"))
17950	(unless fnum (setq fnum (make-vector (length fields) 0)))
17951	(setq nlines (1+ nlines) i -1)
17952	(push (concat "<tr>"
17953		      (mapconcat
17954		       (lambda (x)
17955			 (setq i (1+ i))
17956			 (if (and (< i nlines)
17957				  (string-match org-table-number-regexp x))
17958			     (incf (aref fnum i)))
17959			 (if head
17960			     (concat "<th>" x "</th>")
17961			   (concat "<td>" x "</td>")))
17962		       fields "")
17963		      "</tr>")
17964	      html)))
17965    (unless splice (if tbopen (push "</tbody>" html)))
17966    (unless splice (push "</table>\n" html))
17967    (setq html (nreverse html))
17968    (unless splice
17969      ;; Put in COL tags with the alignment (unfortuntely often ignored...)
17970      (push (mapconcat
17971	     (lambda (x)
17972	       (format "<COL align=\"%s\">"
17973		       (if (> (/ (float x) nlines) org-table-number-fraction)
17974			   "right" "left")))
17975	     fnum "")
17976	    html)
17977      (push org-export-html-table-tag html))
17978    (concat (mapconcat 'identity html "\n") "\n")))
17979
17980(defun org-table-clean-before-export (lines)
17981  "Check if the table has a marking column.
17982If yes remove the column and the special lines."
17983  (if (memq nil
17984	    (mapcar
17985	     (lambda (x) (or (string-match "^[ \t]*|-" x)
17986			     (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
17987	     lines))
17988      (progn
17989	(setq org-table-clean-did-remove-column-1 nil)
17990	lines)
17991    (setq org-table-clean-did-remove-column-1 t)
17992    (delq nil
17993	  (mapcar
17994	   (lambda (x) (if (string-match "^[ \t]*| *[!_^/] *|" x)
17995			   nil ; ignore this line
17996			 (and (or (string-match "^[ \t]*|-+\\+" x)
17997				  (string-match "^[ \t]*|[^|]*|" x))
17998			      (replace-match "|" t t x))))
17999	   lines))))
18000
18001(defun org-fake-empty-table-line (line)
18002  "Replace everything except \"|\" with spaces."
18003  (let ((i (length line))
18004	(newstr (copy-sequence line)))
18005    (while (> i 0)
18006      (setq i (1- i))
18007      (if (not (eq (aref newstr i) ?|))
18008	  (aset newstr i ?\ )))
18009    newstr))
18010
18011(defun org-format-table-table-html (lines)
18012  "Format a table generated by table.el into HTML.
18013This conversion does *not* use `table-generate-source' from table.el.
18014This has the advantage that Org-mode's HTML conversions can be used.
18015But it has the disadvantage, that no cell- or row-spanning is allowed."
18016  (let (line field-buffer
18017	     (head org-export-highlight-first-table-line)
18018	     fields html empty)
18019    (setq html (concat org-export-html-table-tag "\n"))
18020    (while (setq line (pop lines))
18021      (setq empty "&nbsp;")
18022      (catch 'next-line
18023	(if (string-match "^[ \t]*\\+-" line)
18024	    (progn
18025	      (if field-buffer
18026		  (progn
18027		    (setq html (concat
18028				html
18029				"<tr>"
18030				(mapconcat
18031				 (lambda (x)
18032				   (if (equal x "") (setq x empty))
18033				   (if head
18034				       (concat "<th>" x "</th>\n")
18035				     (concat "<td>" x "</td>\n")))
18036				 field-buffer "\n")
18037				"</tr>\n"))
18038		    (setq head nil)
18039		    (setq field-buffer nil)))
18040	      ;; Ignore this line
18041	      (throw 'next-line t)))
18042	;; Break the line into fields and store the fields
18043	(setq fields (org-split-string line "[ \t]*|[ \t]*"))
18044	(if field-buffer
18045	    (setq field-buffer (mapcar
18046				(lambda (x)
18047				  (concat x "<br/>" (pop fields)))
18048				field-buffer))
18049	  (setq field-buffer fields))))
18050    (setq html (concat html "</table>\n"))
18051    html))
18052
18053(defun org-format-table-table-html-using-table-generate-source (lines)
18054  "Format a table into html, using `table-generate-source' from table.el.
18055This has the advantage that cell- or row-spanning is allowed.
18056But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
18057  (require 'table)
18058  (with-current-buffer (get-buffer-create " org-tmp1 ")
18059    (erase-buffer)
18060    (insert (mapconcat 'identity lines "\n"))
18061    (goto-char (point-min))
18062    (if (not (re-search-forward "|[^+]" nil t))
18063	(error "Error processing table"))
18064    (table-recognize-table)
18065    (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
18066    (table-generate-source 'html " org-tmp2 ")
18067    (set-buffer " org-tmp2 ")
18068    (buffer-substring (point-min) (point-max))))
18069
18070(defun org-html-handle-time-stamps (s)
18071  "Format time stamps in string S, or remove them."
18072  (catch 'exit
18073    (let (r b)
18074      (while (string-match org-maybe-keyword-time-regexp s)
18075	(if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
18076	    ;; never export CLOCK
18077	    (throw 'exit ""))
18078	(or b (setq b (substring s 0 (match-beginning 0))))
18079	(if (not org-export-with-timestamps)
18080	    (setq r (concat r (substring s 0 (match-beginning 0)))
18081		  s (substring s (match-end 0)))
18082	  (setq r (concat
18083		   r (substring s 0 (match-beginning 0))
18084		   (if (match-end 1)
18085		       (format "@<span class=\"timestamp-kwd\">%s @</span>"
18086			       (match-string 1 s)))
18087		   (format " @<span class=\"timestamp\">%s@</span>"
18088			   (substring
18089			    (org-translate-time (match-string 3 s)) 1 -1)))
18090		s (substring s (match-end 0)))))
18091      ;; Line break if line started and ended with time stamp stuff
18092      (if (not r)
18093	  s
18094	(setq r (concat r s))
18095	(unless (string-match "\\S-" (concat b s))
18096	  (setq r (concat r "@<br/>")))
18097	r))))
18098
18099(defun org-html-protect (s)
18100  ;; convert & to &amp;, < to &lt; and > to &gt;
18101  (let ((start 0))
18102    (while (string-match "&" s start)
18103      (setq s (replace-match "&amp;" t t s)
18104	    start (1+ (match-beginning 0))))
18105    (while (string-match "<" s)
18106      (setq s (replace-match "&lt;" t t s)))
18107    (while (string-match ">" s)
18108      (setq s (replace-match "&gt;" t t s))))
18109  s)
18110
18111(defun org-export-cleanup-toc-line (s)
18112  "Remove tags and time staps from lines going into the toc."
18113  (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
18114      (setq s (replace-match "" t t s)))
18115  (when org-export-remove-timestamps-from-toc
18116    (while (string-match org-maybe-keyword-time-regexp s)
18117      (setq s (replace-match "" t t s))))
18118  s)
18119
18120(defun org-html-expand (string)
18121  "Prepare STRING for HTML export.  Applies all active conversions.
18122If there are links in the string, don't modify these."
18123  (let* (m s l res)
18124    (while (setq m (string-match org-bracket-link-regexp string))
18125      (setq s (substring string 0 m)
18126	    l (match-string 0 string)
18127	    string (substring string (match-end 0)))
18128      (push (org-html-do-expand s) res)
18129      (push l res))
18130    (push (org-html-do-expand string) res)
18131    (apply 'concat (nreverse res))))
18132
18133(defun org-html-do-expand (s)
18134  "Apply all active conversions to translate special ASCII to HTML."
18135  (setq s (org-html-protect s))
18136  (if org-export-html-expand
18137      (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
18138	(setq s (replace-match "<\\1>" t nil s))))
18139  (if org-export-with-emphasize
18140      (setq s (org-export-html-convert-emphasize s)))
18141  (if org-export-with-sub-superscripts
18142      (setq s (org-export-html-convert-sub-super s)))
18143  (if org-export-with-TeX-macros
18144      (let ((start 0) wd ass)
18145	(while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
18146	  (setq wd (match-string 1 s))
18147	  (if (setq ass (assoc wd org-html-entities))
18148	      (setq s (replace-match (or (cdr ass)
18149					 (concat "&" (car ass) ";"))
18150				     t t s))
18151	    (setq start (+ start (length wd)))))))
18152  s)
18153
18154(defun org-create-multibrace-regexp (left right n)
18155  "Create a regular expression which will match a balanced sexp.
18156Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
18157as single character strings.
18158The regexp returned will match the entire expression including the
18159delimiters.  It will also define a single group which contains the
18160match except for the outermost delimiters.  The maximum depth of
18161stacked delimiters is N.  Escaping delimiters is not possible."
18162  (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
18163	 (or "\\|")
18164	 (re nothing)
18165	 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
18166    (while (> n 1)
18167      (setq n (1- n)
18168	    re (concat re or next)
18169	    next (concat "\\(?:" nothing left next right "\\)+" nothing)))
18170    (concat left "\\(" re "\\)" right)))
18171
18172(defvar org-match-substring-regexp
18173  (concat
18174   "\\([^\\]\\)\\([_^]\\)\\("
18175   "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
18176   "\\|"
18177   "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
18178   "\\|"
18179   "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
18180  "The regular expression matching a sub- or superscript.")
18181
18182(defun org-export-html-convert-sub-super (string)
18183  "Convert sub- and superscripts in STRING to HTML."
18184  (let (key c)
18185    (while (string-match org-match-substring-regexp string)
18186      (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
18187      (setq c (or (match-string 8 string)
18188		  (match-string 6 string)
18189		  (match-string 5 string)))
18190      (setq string (replace-match
18191		    (concat (match-string 1 string)
18192			    "<" key ">" c "</" key ">")
18193		    t t string)))
18194    (while (string-match "\\\\\\([_^]\\)" string)
18195      (setq string (replace-match (match-string 1 string) t t string))))
18196  string)
18197
18198(defun org-export-html-convert-emphasize (string)
18199  "Apply emphasis."
18200  (while (string-match org-emph-re string)
18201    (setq string (replace-match (concat "\\1" (nth 2 (assoc (match-string 3 string) org-emphasis-alist)) "\\4" (nth 3 (assoc (match-string 3 string) org-emphasis-alist)) "\\5") t nil string)))
18202  string)
18203
18204(defvar org-par-open nil)
18205(defun org-open-par ()
18206  "Insert <p>, but first close previous paragraph if any."
18207  (org-close-par-maybe)
18208  (insert "\n<p>")
18209  (setq org-par-open t))
18210(defun org-close-par-maybe ()
18211  "Close paragraph if there is one open."
18212  (when org-par-open
18213    (insert "</p>")
18214    (setq org-par-open nil)))
18215(defun org-close-li ()
18216  "Close <li> if necessary."
18217  (org-close-par-maybe)
18218  (insert "</li>\n"))
18219;  (when (save-excursion
18220;	  (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
18221;    (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
18222;	(insert "</li>"))))
18223
18224(defun org-html-level-start (level title umax with-toc head-count)
18225  "Insert a new level in HTML export.
18226When TITLE is nil, just close all open levels."
18227  (org-close-par-maybe)
18228  (let ((l (1+ (max level umax))))
18229    (while (<= l org-level-max)
18230      (if (aref org-levels-open (1- l))
18231	  (progn
18232	    (org-html-level-close l)
18233	    (aset org-levels-open (1- l) nil)))
18234      (setq l (1+ l)))
18235    (when title
18236      ;; If title is nil, this means this function is called to close
18237      ;; all levels, so the rest is done only if title is given
18238	(when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
18239	  (setq title (replace-match
18240		       (if org-export-with-tags
18241			   (save-match-data
18242			     (concat
18243			      "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
18244			      (mapconcat 'identity (org-split-string
18245						    (match-string 1 title) ":")
18246					 "&nbsp;")
18247			      "</span>"))
18248			 "")
18249		       t t title)))
18250      (if (> level umax)
18251	  (progn
18252	    (if (aref org-levels-open (1- level))
18253		(progn
18254		  (org-close-li)
18255		  (insert "<li>" title "<br/>\n"))
18256	      (aset org-levels-open (1- level) t)
18257	      (org-close-par-maybe)
18258	      (insert "<ul>\n<li>" title "<br/>\n")))
18259	(if org-export-with-section-numbers
18260	    (setq title (concat (org-section-number level) " " title)))
18261	(setq level (+ level org-export-html-toplevel-hlevel -1))
18262	(if with-toc
18263	    (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
18264			    level head-count title level))
18265	  (insert (format "\n<h%d>%s</h%d>\n" level title level)))
18266	(org-open-par)))))
18267
18268(defun org-html-level-close (&rest args)
18269  "Terminate one level in HTML export."
18270  (org-close-li)
18271  (insert "</ul>"))
18272
18273;;; iCalendar export
18274
18275;;;###autoload
18276(defun org-export-icalendar-this-file ()
18277  "Export current file as an iCalendar file.
18278The iCalendar file will be located in the same directory as the Org-mode
18279file, but with extension `.ics'."
18280  (interactive)
18281  (org-export-icalendar nil buffer-file-name))
18282
18283;;;###autoload
18284(defun org-export-icalendar-all-agenda-files ()
18285  "Export all files in `org-agenda-files' to iCalendar .ics files.
18286Each iCalendar file will be located in the same directory as the Org-mode
18287file, but with extension `.ics'."
18288  (interactive)
18289  (apply 'org-export-icalendar nil (org-agenda-files t)))
18290
18291;;;###autoload
18292(defun org-export-icalendar-combine-agenda-files ()
18293  "Export all files in `org-agenda-files' to a single combined iCalendar file.
18294The file is stored under the name `org-combined-agenda-icalendar-file'."
18295  (interactive)
18296  (apply 'org-export-icalendar t (org-agenda-files t)))
18297
18298(defun org-export-icalendar (combine &rest files)
18299  "Create iCalendar files for all elements of FILES.
18300If COMBINE is non-nil, combine all calendar entries into a single large
18301file and store it under the name `org-combined-agenda-icalendar-file'."
18302  (save-excursion
18303    (let* ((dir (org-export-directory
18304		 :ical (list :publishing-directory
18305			     org-export-publishing-directory)))
18306	   file ical-file ical-buffer category started org-agenda-new-buffers)
18307
18308      (when combine
18309	(setq ical-file
18310	      (if (file-name-absolute-p org-combined-agenda-icalendar-file)
18311		  org-combined-agenda-icalendar-file
18312		(expand-file-name org-combined-agenda-icalendar-file dir))
18313	      ical-buffer (org-get-agenda-file-buffer ical-file))
18314	(set-buffer ical-buffer) (erase-buffer))
18315      (while (setq file (pop files))
18316	(catch 'nextfile
18317	  (org-check-agenda-file file)
18318	  (set-buffer (org-get-agenda-file-buffer file))
18319	  (unless combine
18320	    (setq ical-file (concat (file-name-as-directory dir)
18321				    (file-name-sans-extension
18322				     (file-name-nondirectory buffer-file-name))
18323				    ".ics"))
18324	    (setq ical-buffer (org-get-agenda-file-buffer ical-file))
18325	    (with-current-buffer ical-buffer (erase-buffer)))
18326	  (setq category (or org-category
18327			     (file-name-sans-extension
18328			      (file-name-nondirectory buffer-file-name))))
18329	  (if (symbolp category) (setq category (symbol-name category)))
18330	  (let ((standard-output ical-buffer))
18331	    (if combine
18332		(and (not started) (setq started t)
18333		     (org-start-icalendar-file org-icalendar-combined-name))
18334	      (org-start-icalendar-file category))
18335	    (org-print-icalendar-entries combine)
18336	    (when (or (and combine (not files)) (not combine))
18337	      (org-finish-icalendar-file)
18338	      (set-buffer ical-buffer)
18339	      (save-buffer)
18340	      (run-hooks 'org-after-save-iCalendar-file-hook)))))
18341      (org-release-buffers org-agenda-new-buffers))))
18342
18343(defvar org-after-save-iCalendar-file-hook nil
18344  "Hook run after an iCalendar file has been saved.
18345The iCalendar buffer is still current when this hook is run.
18346A good way to use this is to tell a desktop calenndar application to re-read
18347the iCalendar file.")
18348
18349(defun org-print-icalendar-entries (&optional combine)
18350  "Print iCalendar entries for the current Org-mode file to `standard-output'.
18351When COMBINE is non nil, add the category to each line."
18352  (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
18353	(org-category-table (org-get-category-table))
18354	(dts (org-ical-ts-to-string
18355	      (format-time-string (cdr org-time-stamp-formats) (current-time))
18356	      "DTSTART"))
18357	hd ts ts2 state status (inc t) pos
18358	scheduledp deadlinep tmp pri category)
18359    (save-excursion
18360      (goto-char (point-min))
18361      (while (re-search-forward org-ts-regexp nil t)
18362	(setq pos (match-beginning 0)
18363	      ts (match-string 0)
18364	      inc t
18365	      hd (org-get-heading)
18366	      category (org-get-category))
18367	(if (looking-at re2)
18368	    (progn
18369	      (goto-char (match-end 0))
18370	      (setq ts2 (match-string 1) inc nil))
18371	  (setq ts2 ts
18372		tmp (buffer-substring (max (point-min)
18373					     (- pos org-ds-keyword-length))
18374				      pos)
18375		deadlinep (string-match org-deadline-regexp tmp)
18376		scheduledp (string-match org-scheduled-regexp tmp)
18377		;; donep (org-entry-is-done-p)
18378                ))
18379	(if (or (string-match org-tr-regexp hd)
18380		(string-match org-ts-regexp hd))
18381	    (setq hd (replace-match "" t t hd)))
18382	(if (string-match org-bracket-link-regexp hd)
18383	    (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
18384				      (match-string 1 hd))
18385				    t t hd)))
18386	(if deadlinep (setq hd (concat "DL: " hd)))
18387	(if scheduledp (setq hd (concat "S: " hd)))
18388	(princ (format "BEGIN:VEVENT
18389%s
18390%s
18391SUMMARY:%s
18392CATEGORIES:%s
18393END:VEVENT\n"
18394		       (org-ical-ts-to-string ts "DTSTART")
18395		       (org-ical-ts-to-string ts2 "DTEND" inc)
18396		       hd category)))
18397      (when org-icalendar-include-todo
18398	(goto-char (point-min))
18399	(while (re-search-forward org-todo-line-regexp nil t)
18400	  (setq state (match-string 2))
18401	  (setq status (if (equal state org-done-string)
18402			   "COMPLETED" "NEEDS-ACTION"))
18403	  (when (and state
18404		     (or (not (equal state org-done-string))
18405			 (eq org-icalendar-include-todo 'all)))
18406	    (setq hd (match-string 3))
18407	    (if (string-match org-priority-regexp hd)
18408		(setq pri (string-to-char (match-string 2 hd))
18409		      hd (concat (substring hd 0 (match-beginning 1))
18410				 (substring hd (match-end 1))))
18411	      (setq pri org-default-priority))
18412	    (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
18413					  (- org-lowest-priority ?A))))))
18414
18415	    (princ (format "BEGIN:VTODO
18416%s
18417SUMMARY:%s
18418CATEGORIES:%s
18419SEQUENCE:1
18420PRIORITY:%d
18421STATUS:%s
18422END:VTODO\n"
18423			   dts hd category pri status))))))))
18424
18425(defun org-start-icalendar-file (name)
18426  "Start an iCalendar file by inserting the header."
18427  (let ((user user-full-name)
18428	(name (or name "unknown"))
18429	(timezone (cadr (current-time-zone))))
18430    (princ
18431     (format "BEGIN:VCALENDAR
18432VERSION:2.0
18433X-WR-CALNAME:%s
18434PRODID:-//%s//Emacs with Org-mode//EN
18435X-WR-TIMEZONE:%s
18436CALSCALE:GREGORIAN\n" name user timezone))))
18437
18438(defun org-finish-icalendar-file ()
18439  "Finish an iCalendar file by inserting the END statement."
18440  (princ "END:VCALENDAR\n"))
18441
18442(defun org-ical-ts-to-string (s keyword &optional inc)
18443  "Take a time string S and convert it to iCalendar format.
18444KEYWORD is added in front, to make a complete line like DTSTART....
18445When INC is non-nil, increase the hour by two (if time string contains
18446a time), or the day by one (if it does not contain a time)."
18447  (let ((t1 (org-parse-time-string s 'nodefault))
18448	t2 fmt have-time time)
18449    (if (and (car t1) (nth 1 t1) (nth 2 t1))
18450	(setq t2 t1 have-time t)
18451      (setq t2 (org-parse-time-string s)))
18452    (let ((s (car t2))   (mi (nth 1 t2)) (h (nth 2 t2))
18453	  (d (nth 3 t2)) (m  (nth 4 t2)) (y (nth 5 t2)))
18454      (when inc
18455	(if have-time (setq h (+ 2 h)) (setq d (1+ d))))
18456      (setq time (encode-time s mi h d m y)))
18457    (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
18458    (concat keyword (format-time-string fmt time))))
18459
18460;;; XOXO export
18461
18462(defun org-export-as-xoxo-insert-into (buffer &rest output)
18463  (with-current-buffer buffer
18464    (apply 'insert output)))
18465(put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
18466
18467(defun org-export-as-xoxo (&optional buffer)
18468  "Export the org buffer as XOXO.
18469The XOXO buffer is named *xoxo-<source buffer name>*"
18470  (interactive (list (current-buffer)))
18471  ;; A quickie abstraction
18472
18473  ;; Output everything as XOXO
18474  (with-current-buffer (get-buffer buffer)
18475    (goto-char (point-min))  ;; CD:  beginning-of-buffer is not allowed.
18476    (let* ((opt-plist (org-combine-plists (org-default-export-plist)
18477					(org-infile-export-plist)))
18478	   (filename (concat (file-name-as-directory
18479			      (org-export-directory :xoxo opt-plist))
18480			     (file-name-sans-extension
18481			      (file-name-nondirectory buffer-file-name))
18482			     ".html"))
18483	   (out (find-file-noselect filename))
18484	   (last-level 1)
18485	   (hanging-li nil))
18486      ;; Check the output buffer is empty.
18487      (with-current-buffer out (erase-buffer))
18488      ;; Kick off the output
18489      (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
18490      (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
18491        (let* ((hd (match-string-no-properties 1))
18492               (level (length hd))
18493               (text (concat
18494                      (match-string-no-properties 2)
18495                      (save-excursion
18496                        (goto-char (match-end 0))
18497                        (let ((str ""))
18498                          (catch 'loop
18499                            (while 't
18500                              (forward-line)
18501                              (if (looking-at "^[ \t]\\(.*\\)")
18502                                  (setq str (concat str (match-string-no-properties 1)))
18503                                (throw 'loop str)))))))))
18504
18505          ;; Handle level rendering
18506          (cond
18507           ((> level last-level)
18508            (org-export-as-xoxo-insert-into out "\n<ol>\n"))
18509
18510           ((< level last-level)
18511            (dotimes (- (- last-level level) 1)
18512              (if hanging-li
18513                  (org-export-as-xoxo-insert-into out "</li>\n"))
18514              (org-export-as-xoxo-insert-into out "</ol>\n"))
18515            (when hanging-li
18516              (org-export-as-xoxo-insert-into out "</li>\n")
18517              (setq hanging-li nil)))
18518
18519           ((equal level last-level)
18520            (if hanging-li
18521                (org-export-as-xoxo-insert-into out "</li>\n")))
18522           )
18523
18524          (setq last-level level)
18525
18526          ;; And output the new li
18527          (setq hanging-li 't)
18528          (if (equal ?+ (elt text 0))
18529              (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
18530            (org-export-as-xoxo-insert-into out "<li>" text))))
18531
18532      ;; Finally finish off the ol
18533      (dotimes (- last-level 1)
18534        (if hanging-li
18535            (org-export-as-xoxo-insert-into out "</li>\n"))
18536        (org-export-as-xoxo-insert-into out "</ol>\n"))
18537
18538      ;; Finish the buffer off and clean it up.
18539      (switch-to-buffer-other-window out)
18540      (indent-region (point-min) (point-max) nil)
18541      (save-buffer)
18542      (goto-char (point-min))
18543      )))
18544
18545
18546;;;; Key bindings
18547
18548;; - Bindings in Org-mode map are currently
18549;;   0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t  the alphabet
18550;;             abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/=     [] ; |,.<>~ '\t  necessary bindings
18551;;                 e                                                        (?) useful from outline-mode
18552;;                     i k                 @                                expendable from outline-mode
18553;;   0123456789                               % &     ()_{}    "      `     free
18554
18555;; Make `C-c C-x' a prefix key
18556(define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
18557
18558;; TAB key with modifiers
18559(define-key org-mode-map "\C-i"       'org-cycle)
18560(define-key org-mode-map [(tab)]      'org-cycle)
18561(define-key org-mode-map [(control tab)] 'org-force-cycle-archived)
18562(define-key org-mode-map [(meta tab)] 'org-complete)
18563(define-key org-mode-map "\M-\t" 'org-complete)
18564(define-key org-mode-map "\M-\C-i"      'org-complete)
18565;; The following line is necessary under Suse GNU/Linux
18566(unless (featurep 'xemacs)
18567  (define-key org-mode-map [S-iso-lefttab]  'org-shifttab))
18568(define-key org-mode-map [(shift tab)]    'org-shifttab)
18569
18570(define-key org-mode-map (org-key 'S-return)   'org-table-copy-down)
18571(define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18572(define-key org-mode-map [(meta return)]       'org-meta-return)
18573
18574;; Cursor keys with modifiers
18575(define-key org-mode-map [(meta left)]  'org-metaleft)
18576(define-key org-mode-map [(meta right)] 'org-metaright)
18577(define-key org-mode-map [(meta up)]    'org-metaup)
18578(define-key org-mode-map [(meta down)]  'org-metadown)
18579
18580(define-key org-mode-map [(meta shift left)]   'org-shiftmetaleft)
18581(define-key org-mode-map [(meta shift right)]  'org-shiftmetaright)
18582(define-key org-mode-map [(meta shift up)]     'org-shiftmetaup)
18583(define-key org-mode-map [(meta shift down)]   'org-shiftmetadown)
18584
18585(define-key org-mode-map (org-key 'S-up)       'org-shiftup)
18586(define-key org-mode-map (org-key 'S-down)     'org-shiftdown)
18587(define-key org-mode-map (org-key 'S-left)     'org-shiftleft)
18588(define-key org-mode-map (org-key 'S-right)    'org-shiftright)
18589
18590;;; Extra keys for tty access.
18591;;  We only set them when really needed because otherwise the
18592;;  menus don't show the simple keys
18593
18594(when (or (featurep 'xemacs)   ;; because XEmacs supports multi-device stuff
18595	  (not window-system))
18596  (define-key org-mode-map "\C-c\C-xc"    'org-table-copy-down)
18597  (define-key org-mode-map "\C-c\C-xM"    'org-insert-todo-heading)
18598  (define-key org-mode-map "\C-c\C-xm"    'org-meta-return)
18599  (define-key org-mode-map [?\e (return)] 'org-meta-return)
18600  (define-key org-mode-map [?\e (left)]   'org-metaleft)
18601  (define-key org-mode-map "\C-c\C-xl"    'org-metaleft)
18602  (define-key org-mode-map [?\e (right)]  'org-metaright)
18603  (define-key org-mode-map "\C-c\C-xr"    'org-metaright)
18604  (define-key org-mode-map [?\e (up)]     'org-metaup)
18605  (define-key org-mode-map "\C-c\C-xu"    'org-metaup)
18606  (define-key org-mode-map [?\e (down)]   'org-metadown)
18607  (define-key org-mode-map "\C-c\C-xd"    'org-metadown)
18608  (define-key org-mode-map "\C-c\C-xL"    'org-shiftmetaleft)
18609  (define-key org-mode-map "\C-c\C-xR"    'org-shiftmetaright)
18610  (define-key org-mode-map "\C-c\C-xU"    'org-shiftmetaup)
18611  (define-key org-mode-map "\C-c\C-xD"    'org-shiftmetadown)
18612  (define-key org-mode-map [?\C-c ?\C-x (up)]    'org-shiftup)
18613  (define-key org-mode-map [?\C-c ?\C-x (down)]  'org-shiftdown)
18614  (define-key org-mode-map [?\C-c ?\C-x (left)]  'org-shiftleft)
18615  (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright))
18616
18617  ;; All the other keys
18618
18619(define-key org-mode-map "\C-c\C-a" 'show-all)  ; in case allout messed up.
18620(define-key org-mode-map "\C-c\C-r" 'org-reveal)
18621(define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
18622(define-key org-mode-map "\C-c$"    'org-archive-subtree)
18623(define-key org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18624(define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
18625(define-key org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18626(define-key org-mode-map "\C-c\C-j" 'org-goto)
18627(define-key org-mode-map "\C-c\C-t" 'org-todo)
18628(define-key org-mode-map "\C-c\C-s" 'org-schedule)
18629(define-key org-mode-map "\C-c\C-d" 'org-deadline)
18630(define-key org-mode-map "\C-c;"    'org-toggle-comment)
18631(define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
18632(define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
18633(define-key org-mode-map "\C-c/"    'org-occur)   ; Minor-mode reserved
18634(define-key org-mode-map "\C-c\\"   'org-tags-sparse-tree) ; Minor-mode res.
18635(define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
18636(define-key org-mode-map "\M-\C-m"  'org-insert-heading)
18637(define-key org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18638(define-key org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18639(define-key org-mode-map "\C-c\C-l" 'org-insert-link)
18640(define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
18641(define-key org-mode-map "\C-c%"    'org-mark-ring-push)
18642(define-key org-mode-map "\C-c&"    'org-mark-ring-goto)
18643(define-key org-mode-map "\C-c\C-z" 'org-time-stamp)  ; Alternative binding
18644(define-key org-mode-map "\C-c."    'org-time-stamp)  ; Minor-mode reserved
18645(define-key org-mode-map "\C-c!"    'org-time-stamp-inactive) ; Minor-mode r.
18646(define-key org-mode-map "\C-c,"    'org-priority)    ; Minor-mode reserved
18647(define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18648(define-key org-mode-map "\C-c>"    'org-goto-calendar)
18649(define-key org-mode-map "\C-c<"    'org-date-from-calendar)
18650(define-key org-mode-map [(control ?,)]     'org-cycle-agenda-files)
18651(define-key org-mode-map [(control ?\')]     'org-cycle-agenda-files)
18652(define-key org-mode-map "\C-c["    'org-agenda-file-to-front)
18653(define-key org-mode-map "\C-c]"    'org-remove-file)
18654(define-key org-mode-map "\C-c-"    'org-table-insert-hline)
18655(define-key org-mode-map "\C-c^"    'org-sort)
18656(define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18657(define-key org-mode-map "\C-c#"    'org-update-checkbox-count)
18658(define-key org-mode-map "\C-m"     'org-return)
18659(define-key org-mode-map "\C-c?"    'org-table-field-info)
18660(define-key org-mode-map "\C-c "    'org-table-blank-field)
18661(define-key org-mode-map "\C-c+"    'org-table-sum)
18662(define-key org-mode-map "\C-c="    'org-table-eval-formula)
18663(define-key org-mode-map "\C-c'"    'org-table-edit-formulas)
18664(define-key org-mode-map "\C-c`"    'org-table-edit-field)
18665(define-key org-mode-map "\C-c|"    'org-table-create-or-convert-from-region)
18666(define-key org-mode-map "\C-c*"    'org-table-recalculate)
18667(define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18668(define-key org-mode-map "\C-c~"    'org-table-create-with-table.el)
18669(define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
18670(define-key org-mode-map "\C-c}"    'org-table-toggle-coordinate-overlays)
18671(define-key org-mode-map "\C-c{"    'org-table-toggle-formula-debugger)
18672(define-key org-mode-map "\C-c\C-e" 'org-export)
18673(define-key org-mode-map "\C-c:"    'org-toggle-fixed-width-section)
18674
18675(define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
18676(define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18677(define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18678(define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18679
18680(define-key org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18681(define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18682(define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18683(define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
18684(define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18685(define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18686(define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18687(define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18688(define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18689
18690(when (featurep 'xemacs)
18691  (define-key org-mode-map 'button3   'popup-mode-menu))
18692
18693(defsubst org-table-p () (org-at-table-p))
18694
18695(defun org-self-insert-command (N)
18696  "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18697If the cursor is in a table looking at whitespace, the whitespace is
18698overwritten, and the table is not marked as requiring realignment."
18699  (interactive "p")
18700  (if (and (org-table-p)
18701	   (progn
18702	     ;; check if we blank the field, and if that triggers align
18703	     (and org-table-auto-blank-field
18704		  (member last-command
18705			  '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
18706		  (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]*  |"))
18707		      ;; got extra space, this field does not determine column width
18708		      (let (org-table-may-need-update) (org-table-blank-field))
18709		    ;; no extra space, this field may determine column width
18710		    (org-table-blank-field)))
18711	     t)
18712	   (eq N 1)
18713	   (looking-at "[^|\n]*  |"))
18714      (let (org-table-may-need-update)
18715	(goto-char (1- (match-end 0)))
18716	(delete-backward-char 1)
18717	(goto-char (match-beginning 0))
18718	(self-insert-command N))
18719    (setq org-table-may-need-update t)
18720    (self-insert-command N)))
18721
18722(defun org-delete-backward-char (N)
18723  "Like `delete-backward-char', insert whitespace at field end in tables.
18724When deleting backwards, in tables this function will insert whitespace in
18725front of the next \"|\" separator, to keep the table aligned.  The table will
18726still be marked for re-alignment if the field did fill the entire column,
18727because, in this case the deletion might narrow the column."
18728  (interactive "p")
18729  (if (and (org-table-p)
18730	   (eq N 1)
18731	   (string-match "|" (buffer-substring (point-at-bol) (point)))
18732	   (looking-at ".*?|"))
18733      (let ((pos (point))
18734	    (noalign (looking-at "[^|\n\r]*  |"))
18735	    (c org-table-may-need-update))
18736	(backward-delete-char N)
18737	(skip-chars-forward "^|")
18738	(insert " ")
18739	(goto-char (1- pos))
18740	;; noalign: if there were two spaces at the end, this field
18741	;; does not determine the width of the column.
18742	(if noalign (setq org-table-may-need-update c)))
18743    (backward-delete-char N)))
18744
18745(defun org-delete-char (N)
18746  "Like `delete-char', but insert whitespace at field end in tables.
18747When deleting characters, in tables this function will insert whitespace in
18748front of the next \"|\" separator, to keep the table aligned.  The table will
18749still be marked for re-alignment if the field did fill the entire column,
18750because, in this case the deletion might narrow the column."
18751  (interactive "p")
18752  (if (and (org-table-p)
18753	   (not (bolp))
18754	   (not (= (char-after) ?|))
18755	   (eq N 1))
18756      (if (looking-at ".*?|")
18757	  (let ((pos (point))
18758		(noalign (looking-at "[^|\n\r]*  |"))
18759		(c org-table-may-need-update))
18760	    (replace-match (concat
18761			    (substring (match-string 0) 1 -1)
18762			    " |"))
18763	    (goto-char pos)
18764	    ;; noalign: if there were two spaces at the end, this field
18765	    ;; does not determine the width of the column.
18766	    (if noalign (setq org-table-may-need-update c)))
18767	(delete-char N))
18768    (delete-char N)))
18769
18770;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18771(put 'org-self-insert-command 'delete-selection t)
18772(put 'orgtbl-self-insert-command 'delete-selection t)
18773(put 'org-delete-char 'delete-selection 'supersede)
18774(put 'org-delete-backward-char 'delete-selection 'supersede)
18775
18776;; Make `flyspell-mode' delay after some commands
18777(put 'org-self-insert-command 'flyspell-delayed t)
18778(put 'orgtbl-self-insert-command 'flyspell-delayed t)
18779(put 'org-delete-char 'flyspell-delayed t)
18780(put 'org-delete-backward-char 'flyspell-delayed t)
18781
18782
18783;; How to do this: Measure non-white length of current string
18784;; If equal to column width, we should realign.
18785
18786(defun org-remap (map &rest commands)
18787  "In MAP, remap the functions given in COMMANDS.
18788COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18789  (let (new old)
18790    (while commands
18791      (setq old (pop commands) new (pop commands))
18792      (if (fboundp 'command-remapping)
18793	  (define-key map (vector 'remap old) new)
18794	(substitute-key-definition old new map global-map)))))
18795
18796(when (eq org-enable-table-editor 'optimized)
18797  ;; If the user wants maximum table support, we need to hijack
18798  ;; some standard editing functions
18799  (org-remap org-mode-map
18800	     'self-insert-command 'org-self-insert-command
18801	     'delete-char 'org-delete-char
18802	     'delete-backward-char 'org-delete-backward-char)
18803  (define-key org-mode-map "|" 'org-force-self-insert))
18804
18805(defun org-shiftcursor-error ()
18806  "Throw an error because Shift-Cursor command was applied in wrong context."
18807  (error "This command is active in special context like tables, headlines or timestamps"))
18808
18809(defun org-shifttab (&optional arg)
18810  "Global visibility cycling or move to previous table field.
18811Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18812on context.
18813See the individual commands for more information."
18814  (interactive "P")
18815  (cond
18816   ((org-at-table-p) (call-interactively 'org-table-previous-field))
18817   (arg (message  "Content view to level: ")
18818	(org-content (prefix-numeric-value arg))
18819	(setq org-cycle-global-status 'overview))
18820   (t (call-interactively 'org-global-cycle))))
18821
18822(defun org-shiftmetaleft ()
18823  "Promote subtree or delete table column.
18824Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
18825See the individual commands for more information."
18826  (interactive)
18827  (cond
18828   ((org-at-table-p) (call-interactively 'org-table-delete-column))
18829   ((org-on-heading-p) (call-interactively 'org-promote-subtree))
18830   ((org-at-item-p) (call-interactively 'org-outdent-item))
18831   (t (org-shiftcursor-error))))
18832
18833(defun org-shiftmetaright ()
18834  "Demote subtree or insert table column.
18835Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
18836See the individual commands for more information."
18837  (interactive)
18838  (cond
18839   ((org-at-table-p) (call-interactively 'org-table-insert-column))
18840   ((org-on-heading-p) (call-interactively 'org-demote-subtree))
18841   ((org-at-item-p) (call-interactively 'org-indent-item))
18842   (t (org-shiftcursor-error))))
18843
18844(defun org-shiftmetaup (&optional arg)
18845  "Move subtree up or kill table row.
18846Calls `org-move-subtree-up' or `org-table-kill-row' or
18847`org-move-item-up' depending on context.  See the individual commands
18848for more information."
18849  (interactive "P")
18850  (cond
18851   ((org-at-table-p) (call-interactively 'org-table-kill-row))
18852   ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
18853   ((org-at-item-p) (call-interactively 'org-move-item-up))
18854   (t (org-shiftcursor-error))))
18855(defun org-shiftmetadown (&optional arg)
18856  "Move subtree down or insert table row.
18857Calls `org-move-subtree-down' or `org-table-insert-row' or
18858`org-move-item-down', depending on context.  See the individual
18859commands for more information."
18860  (interactive "P")
18861  (cond
18862   ((org-at-table-p) (call-interactively 'org-table-insert-row))
18863   ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
18864   ((org-at-item-p) (call-interactively 'org-move-item-down))
18865   (t (org-shiftcursor-error))))
18866
18867(defun org-metaleft (&optional arg)
18868  "Promote heading or move table column to left.
18869Calls `org-do-promote' or `org-table-move-column', depending on context.
18870With no specific context, calls the Emacs default `backward-word'.
18871See the individual commands for more information."
18872  (interactive "P")
18873  (cond
18874   ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18875   ((or (org-on-heading-p) (org-region-active-p))
18876    (call-interactively 'org-do-promote))
18877   ((org-at-item-p) (call-interactively 'org-outdent-item))
18878   (t (call-interactively 'backward-word))))
18879
18880(defun org-metaright (&optional arg)
18881  "Demote subtree or move table column to right.
18882Calls `org-do-demote' or `org-table-move-column', depending on context.
18883With no specific context, calls the Emacs default `forward-word'.
18884See the individual commands for more information."
18885  (interactive "P")
18886  (cond
18887   ((org-at-table-p) (call-interactively 'org-table-move-column))
18888   ((or (org-on-heading-p) (org-region-active-p))
18889    (call-interactively 'org-do-demote))
18890   ((org-at-item-p) (call-interactively 'org-indent-item))
18891   (t (call-interactively 'forward-word))))
18892
18893(defun org-metaup (&optional arg)
18894  "Move subtree up or move table row up.
18895Calls `org-move-subtree-up' or `org-table-move-row' or
18896`org-move-item-up', depending on context.  See the individual commands
18897for more information."
18898  (interactive "P")
18899  (cond
18900   ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18901   ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
18902   ((org-at-item-p) (call-interactively 'org-move-item-up))
18903   (t (org-shiftcursor-error))))
18904
18905(defun org-metadown (&optional arg)
18906  "Move subtree down or move table row down.
18907Calls `org-move-subtree-down' or `org-table-move-row' or
18908`org-move-item-down', depending on context.  See the individual
18909commands for more information."
18910  (interactive "P")
18911  (cond
18912   ((org-at-table-p) (call-interactively 'org-table-move-row))
18913   ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
18914   ((org-at-item-p) (call-interactively 'org-move-item-down))
18915   (t (org-shiftcursor-error))))
18916
18917(defun org-shiftup (&optional arg)
18918  "Increase item in timestamp or increase priority of current headline.
18919Calls `org-timestamp-up' or `org-priority-up', depending on context.
18920See the individual commands for more information."
18921  (interactive "P")
18922  (cond
18923   ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
18924   ((org-on-heading-p) (call-interactively 'org-priority-up))
18925   ((org-at-item-p) (call-interactively 'org-previous-item))
18926   (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
18927
18928(defun org-shiftdown (&optional arg)
18929  "Decrease item in timestamp or decrease priority of current headline.
18930Calls `org-timestamp-down' or `org-priority-down', depending on context.
18931See the individual commands for more information."
18932  (interactive "P")
18933  (cond
18934   ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
18935   ((org-on-heading-p) (call-interactively 'org-priority-down))
18936   (t (call-interactively 'org-next-item))))
18937
18938(defun org-shiftright ()
18939  "Next TODO keyword or timestamp one day later, depending on context."
18940  (interactive)
18941  (cond
18942   ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18943   ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
18944   (t (org-shiftcursor-error))))
18945
18946(defun org-shiftleft ()
18947  "Previous TODO keyword or timestamp one day earlier, depending on context."
18948  (interactive)
18949  (cond
18950   ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18951   ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
18952   (t (org-shiftcursor-error))))
18953
18954(defun org-copy-special ()
18955  "Copy region in table or copy current subtree.
18956Calls `org-table-copy' or `org-copy-subtree', depending on context.
18957See the individual commands for more information."
18958  (interactive)
18959  (call-interactively
18960   (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18961
18962(defun org-cut-special ()
18963  "Cut region in table or cut current subtree.
18964Calls `org-table-copy' or `org-cut-subtree', depending on context.
18965See the individual commands for more information."
18966  (interactive)
18967  (call-interactively
18968   (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18969
18970(defun org-paste-special (arg)
18971  "Paste rectangular region into table, or past subtree relative to level.
18972Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18973See the individual commands for more information."
18974  (interactive "P")
18975  (if (org-at-table-p)
18976      (org-table-paste-rectangle)
18977    (org-paste-subtree arg)))
18978
18979(defun org-ctrl-c-ctrl-c (&optional arg)
18980  "Set tags in headline, or update according to changed information at point.
18981
18982This command does many different things, depending on context:
18983
18984- If the cursor is in a headline, prompt for tags and insert them
18985  into the current line, aligned to `org-tags-column'.  When called
18986  with prefix arg, realign all tags in the current buffer.
18987
18988- If the cursor is in one of the special #+KEYWORD lines, this
18989  triggers scanning the buffer for these lines and updating the
18990  information.
18991
18992- If the cursor is inside a table, realign the table.  This command
18993  works even if the automatic table editor has been turned off.
18994
18995- If the cursor is on a #+TBLFM line, re-apply the formulas to
18996  the entire table.
18997
18998- If the cursor is inside a table created by the table.el package,
18999  activate that table.
19000
19001- If the current buffer is a remember buffer, close note and file it.
19002  with a prefix argument, file it without further interaction to the default
19003  location.
19004
19005- If the cursor is on a <<<target>>>, update radio targets and corresponding
19006  links in this buffer.
19007
19008- If the cursor is on a numbered item in a plain list, renumber the
19009  ordered list."
19010  (interactive "P")
19011  (let  ((org-enable-table-editor t))
19012    (cond
19013     ((or org-clock-overlays
19014	  org-occur-highlights
19015	  org-latex-fragment-image-overlays)
19016      (org-remove-clock-overlays)
19017      (org-remove-occur-highlights)
19018      (org-remove-latex-fragment-image-overlays)
19019      (message "Temporary highlights/overlays removed from current buffer"))
19020     ((and (local-variable-p 'org-finish-function (current-buffer))
19021	   (fboundp org-finish-function))
19022      (funcall org-finish-function))
19023     ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
19024     ((org-on-heading-p) (call-interactively 'org-set-tags))
19025     ((org-at-table.el-p)
19026      (require 'table)
19027      (beginning-of-line 1)
19028      (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
19029      (call-interactively 'table-recognize-table))
19030     ((org-at-table-p)
19031      (org-table-maybe-eval-formula)
19032      (if arg
19033	  (call-interactively 'org-table-recalculate)
19034	(org-table-maybe-recalculate-line))
19035      (call-interactively 'org-table-align))
19036     ((org-at-item-checkbox-p)
19037      (call-interactively 'org-toggle-checkbox))
19038     ((org-at-item-p)
19039      (call-interactively 'org-renumber-ordered-list))
19040     ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
19041      (cond
19042       ((equal (match-string 1) "TBLFM")
19043	;; Recalculate the table before this line
19044	(save-excursion
19045	  (beginning-of-line 1)
19046	  (skip-chars-backward " \r\n\t")
19047	  (if (org-at-table-p)
19048	      (org-call-with-arg 'org-table-recalculate t))))
19049       (t
19050	(call-interactively 'org-mode-restart))))
19051     (t (error "C-c C-c can do nothing useful at this location.")))))
19052
19053(defun org-mode-restart ()
19054  "Restart Org-mode, to scan again for special lines.
19055Also updates the keyword regular expressions."
19056  (interactive)
19057  (let ((org-inhibit-startup t)) (org-mode))
19058  (message "Org-mode restarted to refresh keyword and special line setup"))
19059
19060(defun org-return ()
19061  "Goto next table row or insert a newline.
19062Calls `org-table-next-row' or `newline', depending on context.
19063See the individual commands for more information."
19064  (interactive)
19065  (cond
19066   ((org-at-table-p)
19067    (org-table-justify-field-maybe)
19068    (call-interactively 'org-table-next-row))
19069   (t (newline))))
19070
19071(defun org-meta-return (&optional arg)
19072  "Insert a new heading or wrap a region in a table.
19073Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19074See the individual commands for more information."
19075  (interactive "P")
19076  (cond
19077   ((org-at-table-p)
19078    (call-interactively 'org-table-wrap-region))
19079   (t (call-interactively 'org-insert-heading))))
19080
19081;;; Menu entries
19082
19083;; Define the Org-mode menus
19084(easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19085  '("Tbl"
19086    ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
19087    ["Next Field" org-cycle (org-at-table-p)]
19088    ["Previous Field" org-shifttab (org-at-table-p)]
19089    ["Next Row" org-return (org-at-table-p)]
19090    "--"
19091    ["Blank Field" org-table-blank-field (org-at-table-p)]
19092    ["Edit Field" org-table-edit-field (org-at-table-p)]
19093    ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19094    "--"
19095    ("Column"
19096     ["Move Column Left" org-metaleft (org-at-table-p)]
19097     ["Move Column Right" org-metaright (org-at-table-p)]
19098     ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19099     ["Insert Column" org-shiftmetaright (org-at-table-p)])
19100    ("Row"
19101     ["Move Row Up" org-metaup (org-at-table-p)]
19102     ["Move Row Down" org-metadown (org-at-table-p)]
19103     ["Delete Row" org-shiftmetaup (org-at-table-p)]
19104     ["Insert Row" org-shiftmetadown (org-at-table-p)]
19105     ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19106     "--"
19107     ["Insert Hline" org-table-insert-hline (org-at-table-p)])
19108    ("Rectangle"
19109     ["Copy Rectangle" org-copy-special (org-at-table-p)]
19110     ["Cut Rectangle" org-cut-special (org-at-table-p)]
19111     ["Paste Rectangle" org-paste-special (org-at-table-p)]
19112     ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19113    "--"
19114    ("Calculate"
19115     ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19116     ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19117     ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
19118     "--"
19119     ["Recalculate line" org-table-recalculate (org-at-table-p)]
19120     ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19121     ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19122     "--"
19123     ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19124     "--"
19125     ["Sum Column/Rectangle" org-table-sum
19126      (or (org-at-table-p) (org-region-active-p))]
19127     ["Which Column?" org-table-current-column (org-at-table-p)])
19128    ["Debug Formulas"
19129     org-table-toggle-formula-debugger
19130     :style toggle :selected org-table-formula-debug]
19131    ["Show Col/Row Numbers"
19132     org-table-toggle-coordinate-overlays
19133     :style toggle :selected org-table-overlay-coordinates]
19134    "--"
19135    ["Create" org-table-create (and (not (org-at-table-p))
19136				    org-enable-table-editor)]
19137    ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19138    ["Import from File" org-table-import (not (org-at-table-p))]
19139    ["Export to File" org-table-export (org-at-table-p)]
19140    "--"
19141    ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19142
19143(easy-menu-define org-org-menu org-mode-map "Org menu"
19144  '("Org"
19145    ("Show/Hide"
19146     ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
19147     ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
19148     ["Sparse Tree" org-occur t]
19149     ["Reveal Context" org-reveal t]
19150     ["Show All" show-all t]
19151     "--"
19152     ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19153    "--"
19154    ["New Heading" org-insert-heading t]
19155    ("Navigate Headings"
19156     ["Up" outline-up-heading t]
19157     ["Next" outline-next-visible-heading t]
19158     ["Previous" outline-previous-visible-heading t]
19159     ["Next Same Level" outline-forward-same-level t]
19160     ["Previous Same Level" outline-backward-same-level t]
19161     "--"
19162     ["Jump" org-goto t])
19163    ("Edit Structure"
19164     ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19165     ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19166     "--"
19167     ["Copy Subtree"  org-copy-special (not (org-at-table-p))]
19168     ["Cut Subtree"  org-cut-special (not (org-at-table-p))]
19169     ["Paste Subtree"  org-paste-special (not (org-at-table-p))]
19170     "--"
19171     ["Promote Heading" org-metaleft (not (org-at-table-p))]
19172     ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19173     ["Demote Heading"  org-metaright (not (org-at-table-p))]
19174     ["Demote Subtree"  org-shiftmetaright (not (org-at-table-p))]
19175     "--"
19176     ["Sort Region/Children" org-sort  (not (org-at-table-p))]
19177     "--"
19178     ["Convert to odd levels" org-convert-to-odd-levels t]
19179     ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19180    ("Archive"
19181     ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19182;     ["Check and Tag Children" (org-toggle-archive-tag (4))
19183;      :active t :keys "C-u C-c C-x C-a"]
19184     ["Sparse trees open ARCHIVE trees"
19185      (setq org-sparse-tree-open-archived-trees
19186	    (not org-sparse-tree-open-archived-trees))
19187      :style toggle :selected org-sparse-tree-open-archived-trees]
19188     ["Cycling opens ARCHIVE trees"
19189      (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
19190      :style toggle :selected org-cycle-open-archived-trees]
19191     ["Agenda includes ARCHIVE trees"
19192      (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
19193      :style toggle :selected (not org-agenda-skip-archived-trees)]
19194     "--"
19195     ["Move Subtree to Archive" org-advertized-archive-subtree t]
19196 ;    ["Check and Move Children" (org-archive-subtree '(4))
19197 ;     :active t :keys "C-u C-c C-x C-s"]
19198     )
19199    "--"
19200    ("TODO Lists"
19201     ["TODO/DONE/-" org-todo t]
19202     ("Select keyword"
19203      ["Next keyword" org-shiftright (org-on-heading-p)]
19204      ["Previous keyword" org-shiftleft (org-on-heading-p)]
19205      ["Complete Keyword" org-complete (assq :todo-keyword (org-context))])
19206     ["Show TODO Tree" org-show-todo-tree t]
19207     ["Global TODO list" org-todo-list t]
19208     "--"
19209     ["Set Priority" org-priority t]
19210     ["Priority Up" org-shiftup t]
19211     ["Priority Down" org-shiftdown t]
19212     "--"
19213;     ["Insert Checkbox" org-insert-todo-heading (org-in-item-p)]
19214;     ["Toggle Checkbox" org-ctrl-c-ctrl-c (org-at-item-checkbox-p)]
19215;     ["Insert [n/m] cookie" (progn (insert "[/]") (org-update-checkbox-count))
19216;      (or (org-on-heading-p) (org-at-item-p))]
19217;     ["Insert [%] cookie" (progn (insert "[%]") (org-update-checkbox-count))
19218;      (or (org-on-heading-p) (org-at-item-p))]
19219;     ["Update Statistics" org-update-checkbox-count t]
19220     )
19221    ("Dates and Scheduling"
19222     ["Timestamp" org-time-stamp t]
19223     ["Timestamp (inactive)" org-time-stamp-inactive t]
19224     ("Change Date"
19225      ["1 Day Later" org-shiftright t]
19226      ["1 Day Earlier" org-shiftleft t]
19227      ["1 ... Later" org-shiftup t]
19228      ["1 ... Earlier" org-shiftdown t])
19229     ["Compute Time Range" org-evaluate-time-range t]
19230     ["Schedule Item" org-schedule t]
19231     ["Deadline" org-deadline t]
19232     "--"
19233     ["Custom time format" org-toggle-time-stamp-overlays
19234      :style radio :selected org-display-custom-times]
19235     "--"
19236     ["Goto Calendar" org-goto-calendar t]
19237     ["Date from Calendar" org-date-from-calendar t])
19238    ("Logging work"
19239     ["Clock in" org-clock-in t]
19240     ["Clock out" org-clock-out t]
19241     ["Clock cancel" org-clock-cancel t]
19242     ["Display times" org-clock-display t]
19243     ["Create clock table" org-clock-report t]
19244     "--"
19245     ["Record DONE time"
19246      (progn (setq org-log-done (not org-log-done))
19247	     (message "Switching to %s will %s record a timestamp"
19248		      org-done-string
19249		      (if org-log-done "automatically" "not")))
19250      :style toggle :selected org-log-done])
19251    "--"
19252    ["Agenda Command..." org-agenda t]
19253    ("File List for Agenda")
19254    ("Special views current file"
19255     ["TODO Tree"  org-show-todo-tree t]
19256     ["Check Deadlines" org-check-deadlines t]
19257     ["Timeline" org-timeline t]
19258     ["Tags Tree" org-tags-sparse-tree t])
19259    "--"
19260    ("Hyperlinks"
19261     ["Store Link (Global)" org-store-link t]
19262     ["Insert Link" org-insert-link t]
19263     ["Follow Link" org-open-at-point t]
19264     "--"
19265     ["Next link" org-next-link t]
19266     ["Previous link" org-previous-link t]
19267     "--"
19268     ["Descriptive Links"
19269      (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
19270      :style radio :selected (member '(org-link) buffer-invisibility-spec)]
19271     ["Literal Links"
19272      (progn
19273	(org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
19274      :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
19275    "--"
19276    ["Export/Publish..." org-export t]
19277    ("LaTeX"
19278     ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19279      :selected org-cdlatex-mode]
19280     ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19281     ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19282     ["Modify math symbol" org-cdlatex-math-modify
19283      (org-inside-LaTeX-fragment-p)]
19284     ["Export LaTeX fragments as images"
19285      (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
19286      :style toggle :selected org-export-with-LaTeX-fragments])
19287    "--"
19288    ("Documentation"
19289     ["Show Version" org-version t]
19290     ["Info Documentation" org-info t])
19291    ("Customize"
19292     ["Browse Org Group" org-customize t]
19293     "--"
19294     ["Expand This Menu" org-create-customize-menu
19295      (fboundp 'customize-menu-create)])
19296    "--"
19297    ["Refresh setup" org-mode-restart t]
19298    ))
19299
19300(defun org-toggle-log-option (type)
19301  (if (not (listp org-log-done)) (setq org-log-done nil))
19302  (if (memq type org-log-done)
19303      (setq org-log-done (delq type org-log-done))
19304    (add-to-list 'org-log-done type)))
19305
19306(defun org-check-log-option (type)
19307  (and (listp org-log-done) (memq type org-log-done)))
19308
19309(defun org-info (&optional node)
19310  "Read documentation for Org-mode in the info system.
19311With optional NODE, go directly to that node."
19312  (interactive)
19313  (require 'info)
19314  (Info-goto-node (format "(org)%s" (or node ""))))
19315
19316(defun org-install-agenda-files-menu ()
19317  (let ((bl (buffer-list)))
19318    (save-excursion
19319      (while bl
19320	(set-buffer (pop bl))
19321	(if (org-mode-p) (setq bl nil)))
19322      (when (org-mode-p)
19323	(easy-menu-change
19324	 '("Org") "File List for Agenda"
19325	 (append
19326	  (list
19327	   ["Edit File List" (org-edit-agenda-file-list) t]
19328	   ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19329	   ["Remove Current File from List" org-remove-file t]
19330	   ["Cycle through agenda files" org-cycle-agenda-files t]
19331	   "--")
19332	  (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19333
19334;;;; Documentation
19335
19336(defun org-customize ()
19337  "Call the customize function with org as argument."
19338  (interactive)
19339  (customize-browse 'org))
19340
19341(defun org-create-customize-menu ()
19342  "Create a full customization menu for Org-mode, insert it into the menu."
19343  (interactive)
19344  (if (fboundp 'customize-menu-create)
19345      (progn
19346	(easy-menu-change
19347	 '("Org") "Customize"
19348	 `(["Browse Org group" org-customize t]
19349	   "--"
19350	   ,(customize-menu-create 'org)
19351	   ["Set" Custom-set t]
19352	   ["Save" Custom-save t]
19353	   ["Reset to Current" Custom-reset-current t]
19354	   ["Reset to Saved" Custom-reset-saved t]
19355	   ["Reset to Standard Settings" Custom-reset-standard t]))
19356	(message "\"Org\"-menu now contains full customization menu"))
19357    (error "Cannot expand menu (outdated version of cus-edit.el)")))
19358
19359;;;; Miscellaneous stuff
19360
19361
19362;;; Generally useful functions
19363
19364(defun org-context ()
19365  "Return a list of contexts of the current cursor position.
19366If several contexts apply, all are returned.
19367Each context entry is a list with a symbol naming the context, and
19368two positions indicating start and end of the context.  Possible
19369contexts are:
19370
19371:headline         anywhere in a headline
19372:headline-stars   on the leading stars in a headline
19373:todo-keyword     on a TODO keyword (including DONE) in a headline
19374:tags             on the TAGS in a headline
19375:priority         on the priority cookie in a headline
19376:item             on the first line of a plain list item
19377:item-bullet      on the bullet/number of a plain list item
19378:checkbox         on the checkbox in a plain list item
19379:table            in an org-mode table
19380:table-special    on a special filed in a table
19381:table-table      in a table.el table
19382:link             on a hyperlink
19383:keyword          on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19384:target           on a <<target>>
19385:radio-target     on a <<<radio-target>>>
19386:latex-fragment   on a LaTeX fragment
19387:latex-preview    on a LaTeX fragment with overlayed preview image
19388
19389This function expects the position to be visible because it uses font-lock
19390faces as a help to recognize the following contexts: :table-special, :link,
19391and :keyword."
19392  (let* ((f (get-text-property (point) 'face))
19393	 (faces (if (listp f) f (list f)))
19394	 (p (point)) clist o)
19395    ;; First the large context
19396    (cond
19397     ((org-on-heading-p)
19398      (push (list :headline (point-at-bol) (point-at-eol)) clist)
19399      (when (progn
19400	      (beginning-of-line 1)
19401	      (looking-at org-todo-line-tags-regexp))
19402	(push (org-point-in-group p 1 :headline-stars) clist)
19403	(push (org-point-in-group p 2 :todo-keyword) clist)
19404	(push (org-point-in-group p 4 :tags) clist))
19405      (goto-char p)
19406      (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
19407      (if (looking-at "\\[#[A-Z]\\]")
19408	  (push (org-point-in-group p 0 :priority) clist)))
19409
19410     ((org-at-item-p)
19411      (push (org-point-in-group p 2 :item-bullet) clist)
19412      (push (list :item (point-at-bol)
19413		  (save-excursion (org-end-of-item) (point)))
19414	    clist)
19415      (and (org-at-item-checkbox-p)
19416	   (push (org-point-in-group p 0 :checkbox) clist)))
19417
19418     ((org-at-table-p)
19419      (push (list :table (org-table-begin) (org-table-end)) clist)
19420      (if (memq 'org-formula faces)
19421	  (push (list :table-special
19422		      (previous-single-property-change p 'face)
19423		      (next-single-property-change p 'face)) clist)))
19424     ((org-at-table-p 'any)
19425      (push (list :table-table) clist)))
19426    (goto-char p)
19427
19428    ;; Now the small context
19429    (cond
19430     ((org-at-timestamp-p)
19431      (push (org-point-in-group p 0 :timestamp) clist))
19432     ((memq 'org-link faces)
19433      (push (list :link
19434		  (previous-single-property-change p 'face)
19435		  (next-single-property-change p 'face)) clist))
19436     ((memq 'org-special-keyword faces)
19437      (push (list :keyword
19438		  (previous-single-property-change p 'face)
19439		  (next-single-property-change p 'face)) clist))
19440     ((org-on-target-p)
19441      (push (org-point-in-group p 0 :target) clist)
19442      (goto-char (1- (match-beginning 0)))
19443      (if (looking-at org-radio-target-regexp)
19444	  (push (org-point-in-group p 0 :radio-target) clist))
19445      (goto-char p))
19446     ((setq o (car (delq nil
19447			 (mapcar
19448			  (lambda (x)
19449			    (if (memq x org-latex-fragment-image-overlays) x))
19450			  (org-overlays-at (point))))))
19451      (push (list :latex-fragment
19452		  (org-overlay-start o) (org-overlay-end o)) clist)
19453      (push (list :latex-preview
19454		  (org-overlay-start o) (org-overlay-end o)) clist))
19455     ((org-inside-LaTeX-fragment-p)
19456      ;; FIXME: positions wrong.
19457      (push (list :latex-fragment (point) (point)) clist)))
19458
19459    (setq clist (nreverse (delq nil clist)))
19460    clist))
19461
19462(defun org-in-regexp (re &optional nlines visually)
19463  "Check if point is inside a match of regexp.
19464Normally only the current line is checked, but you can include NLINES extra
19465lines both before and after point into the search.
19466If VISUALLY is set, require that the cursor is not after the match but
19467really on, so that the block visually is on the match."
19468  (catch 'exit
19469    (let ((pos (point))
19470          (eol (point-at-eol (+ 1 (or nlines 0))))
19471	  (inc (if visually 1 0)))
19472      (save-excursion
19473	(beginning-of-line (- 1 (or nlines 0)))
19474	(while (re-search-forward re eol t)
19475	  (if (and (<= (match-beginning 0) pos)
19476		   (>= (+ inc (match-end 0)) pos))
19477	      (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19478
19479(defun org-point-in-group (point group &optional context)
19480  "Check if POINT is in match-group GROUP.
19481If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19482match.  If the match group does ot exist or point is not inside it,
19483return nil."
19484  (and (match-beginning group)
19485       (>= point (match-beginning group))
19486       (<= point (match-end group))
19487       (if context
19488	   (list context (match-beginning group) (match-end group))
19489	 t)))
19490
19491(defun org-combine-plists (&rest plists)
19492  "Create a single property list from all plists in PLISTS.
19493The process starts by copying the first list, and then setting properties
19494from the other lists.  Settings in the last list are the most significant
19495ones and overrule settings in the other lists."
19496  (let ((rtn (copy-sequence (pop plists)))
19497	p v ls)
19498    (while plists
19499      (setq ls (pop plists))
19500      (while ls
19501	(setq p (pop ls) v (pop ls))
19502	(setq rtn (plist-put rtn p v))))
19503    rtn))
19504
19505(defun org-move-line-down (arg)
19506  "Move the current line down.  With prefix argument, move it past ARG lines."
19507  (interactive "p")
19508  (let ((col (current-column))
19509	beg end pos)
19510    (beginning-of-line 1) (setq beg (point))
19511    (beginning-of-line 2) (setq end (point))
19512    (beginning-of-line (+ 1 arg))
19513    (setq pos (move-marker (make-marker) (point)))
19514    (insert (delete-and-extract-region beg end))
19515    (goto-char pos)
19516    (move-to-column col)))
19517
19518(defun org-move-line-up (arg)
19519  "Move the current line up.  With prefix argument, move it past ARG lines."
19520  (interactive "p")
19521  (let ((col (current-column))
19522	beg end pos)
19523    (beginning-of-line 1) (setq beg (point))
19524    (beginning-of-line 2) (setq end (point))
19525    (beginning-of-line (- arg))
19526    (setq pos (move-marker (make-marker) (point)))
19527    (insert (delete-and-extract-region beg end))
19528    (goto-char pos)
19529    (move-to-column col)))
19530
19531(defun org-replace-escapes (string table)
19532  "Replace %-escapes in STRING with values in TABLE.
19533TABLE is an association list with keys line \"%a\" and string values.
19534The sequences in STRING may contain normal field width and padding information,
19535for example \"%-5s\".  Replacements happen in the sequence given by TABLE,
19536so values can contain further %-escapes if they are define later in TABLE."
19537  (let ((case-fold-search nil)
19538	e re rpl)
19539    (while (setq e (pop table))
19540      (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19541      (while (string-match re string)
19542	(setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19543			  (cdr e)))
19544	(setq string (replace-match rpl t t string))))
19545    string))
19546
19547
19548(defun org-sublist (list start end)
19549  "Return a section of LIST, from START to END.
19550Counting starts at 1."
19551  (let (rtn (c start))
19552    (setq list (nthcdr (1- start) list))
19553    (while (and list (<= c end))
19554      (push (pop list) rtn)
19555      (setq c (1+ c)))
19556    (nreverse rtn)))
19557
19558(defun org-at-regexp-p (regexp)
19559  "Is point inside a match of REGEXP in the current line?"
19560  (catch 'exit
19561    (save-excursion
19562      (let ((pos (point)) (end (point-at-eol)))
19563	(beginning-of-line 1)
19564	(while (re-search-forward regexp end t)
19565	  (if (and (<= (match-beginning 0) pos)
19566		   (>= (match-end 0) pos))
19567	      (throw 'exit t)))
19568	nil))))
19569
19570(defun org-find-base-buffer-visiting (file)
19571  "Like `find-buffer-visiting' but alway return the base buffer and
19572not an indirect buffer"
19573  (let ((buf (find-buffer-visiting file)))
19574    (or (buffer-base-buffer buf) buf)))
19575
19576;;; Paragraph filling stuff.
19577;; We want this to be just right, so use the full arsenal.
19578;; FIXME: configure filladapt for XEmacs
19579
19580(defun org-set-autofill-regexps ()
19581  (interactive)
19582  ;; In the paragraph separator we include headlines, because filling
19583  ;; text in a line directly attached to a headline would otherwise
19584  ;; fill the headline as well.
19585  (org-set-local 'comment-start-skip "^#+[ \t]*")
19586  (org-set-local 'paragraph-separate "\f\\|\\*\\|[ 	]*$\\|[ \t]*[:|]")
19587  ;; The paragraph starter includes hand-formatted lists.
19588  (org-set-local 'paragraph-start
19589		 "\f\\|[ 	]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
19590  ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19591  ;; But only if the user has not turned off tables or fixed-width regions
19592  (org-set-local
19593   'auto-fill-inhibit-regexp
19594   (concat "\\*\\|#\\+"
19595	   "\\|[ \t]*" org-keyword-time-regexp
19596	   (if (or org-enable-table-editor org-enable-fixed-width-editor)
19597	       (concat
19598		"\\|[ \t]*["
19599		(if org-enable-table-editor "|" "")
19600		(if org-enable-fixed-width-editor ":"  "")
19601		"]"))))
19602  ;; We use our own fill-paragraph function, to make sure that tables
19603  ;; and fixed-width regions are not wrapped.  That function will pass
19604  ;; through to `fill-paragraph' when appropriate.
19605  (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19606  ; Adaptive filling: To get full control, first make sure that
19607  ;; `adaptive-fill-regexp' never matches.  Then install our own matcher.
19608  (org-set-local 'adaptive-fill-regexp "\000")
19609  (org-set-local 'adaptive-fill-function
19610		 'org-adaptive-fill-function))
19611
19612(defun org-fill-paragraph (&optional justify)
19613  "Re-align a table, pass through to fill-paragraph if no table."
19614  (let ((table-p (org-at-table-p))
19615	(table.el-p (org-at-table.el-p)))
19616    (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
19617	  (table.el-p t)                             ; skip table.el tables
19618	  (table-p (org-table-align) t)              ; align org-mode tables
19619	  (t nil))))                                 ; call paragraph-fill
19620
19621;; For reference, this is the default value of adaptive-fill-regexp
19622;;  "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
19623
19624(defun org-adaptive-fill-function ()
19625  "Return a fill prefix for org-mode files.
19626In particular, this makes sure hanging paragraphs for hand-formatted lists
19627work correctly."
19628  (cond ((looking-at "#[ \t]+")
19629	 (match-string 0))
19630	((looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
19631	 (make-string (- (match-end 0) (match-beginning 0)) ?\ ))
19632	(t nil)))
19633
19634
19635(defun org-image-file-name-regexp ()
19636  "Return regexp matching the file names of images."
19637  (if (fboundp 'image-file-name-regexp)
19638      (image-file-name-regexp)
19639    (let ((image-file-name-extensions
19640	   '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19641	     "xbm" "xpm" "pbm" "pgm" "ppm")))
19642      (concat "\\."
19643	      (regexp-opt (nconc (mapcar 'upcase
19644					 image-file-name-extensions)
19645				 image-file-name-extensions)
19646			  t)
19647	      "\\'"))))
19648
19649(defun org-file-image-p (file)
19650  "Return non-nil if FILE is an image."
19651  (save-match-data
19652    (string-match (org-image-file-name-regexp) file)))
19653
19654;;;; Functions extending outline functionality
19655
19656;; C-a should go to the beginning of a *visible* line, also in the
19657;; new outline.el.  I guess this should be patched into Emacs?
19658(defun org-beginning-of-line ()
19659  "Go to the beginning of the current line.  If that is invisible, continue
19660to a visible line beginning.  This makes the function of C-a more intuitive."
19661  (interactive)
19662  (beginning-of-line 1)
19663  (if (bobp)
19664      nil
19665    (backward-char 1)
19666    (if (org-invisible-p)
19667	(while (and (not (bobp)) (org-invisible-p))
19668	  (backward-char 1)
19669	  (beginning-of-line 1))
19670      (forward-char 1))))
19671
19672(define-key org-mode-map "\C-a" 'org-beginning-of-line)
19673
19674(defun org-invisible-p ()
19675  "Check if point is at a character currently not visible."
19676  ;; Early versions of noutline don't have `outline-invisible-p'.
19677  (if (fboundp 'outline-invisible-p)
19678      (outline-invisible-p)
19679    (get-char-property (point) 'invisible)))
19680
19681(defun org-invisible-p2 ()
19682  "Check if point is at a character currently not visible."
19683  (save-excursion
19684    (if (and (eolp) (not (bobp))) (backward-char 1))
19685    ;; Early versions of noutline don't have `outline-invisible-p'.
19686    (if (fboundp 'outline-invisible-p)
19687	(outline-invisible-p)
19688      (get-char-property (point) 'invisible))))
19689
19690(defalias 'org-back-to-heading 'outline-back-to-heading)
19691(defalias 'org-on-heading-p 'outline-on-heading-p)
19692
19693(defun org-on-target-p ()
19694  (or (org-in-regexp org-radio-target-regexp)
19695      (org-in-regexp org-target-regexp)))
19696
19697(defun org-up-heading-all (arg)
19698  "Move to the heading line of which the present line is a subheading.
19699This function considers both visible and invisible heading lines.
19700With argument, move up ARG levels."
19701  (if (fboundp 'outline-up-heading-all)
19702      (outline-up-heading-all arg)   ; emacs 21 version of outline.el
19703    (outline-up-heading arg t)))     ; emacs 22 version of outline.el
19704
19705(defun org-goto-sibling (&optional previous)
19706  "Goto the next sibling, even if it is invisible.
19707When PREVIOUS is set, go to the previous sibling instead.  Returns t
19708when a sibling was found.  When none is found, return nil and don't
19709move point."
19710  (let ((fun (if previous 're-search-backward 're-search-forward))
19711	(pos (point))
19712	(re (concat "^" outline-regexp))
19713	level l)
19714    (org-back-to-heading t)
19715    (setq level (funcall outline-level))
19716    (catch 'exit
19717      (or previous (forward-char 1))
19718      (while (funcall fun re nil t)
19719	(setq l (funcall outline-level))
19720	(when (< l level) (goto-char pos) (throw 'exit nil))
19721	(when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
19722      (goto-char pos)
19723      nil)))
19724
19725(defun org-show-siblings ()
19726  "Show all siblings of the current headline."
19727  (save-excursion
19728    (while (org-goto-sibling) (org-flag-heading nil)))
19729  (save-excursion
19730    (while (org-goto-sibling 'previous)
19731      (org-flag-heading nil))))
19732
19733(defun org-show-hidden-entry ()
19734  "Show an entry where even the heading is hidden."
19735  (save-excursion
19736    (org-show-entry)))
19737
19738(defun org-flag-heading (flag &optional entry)
19739  "Flag the current heading.  FLAG non-nil means make invisible.
19740When ENTRY is non-nil, show the entire entry."
19741  (save-excursion
19742    (org-back-to-heading t)
19743    ;; Check if we should show the entire entry
19744    (if entry
19745	(progn
19746	  (org-show-entry)
19747	  (save-excursion
19748	    (and (outline-next-heading)
19749		 (org-flag-heading nil))))
19750      (outline-flag-region (max 1 (1- (point)))
19751			   (save-excursion (outline-end-of-heading) (point))
19752			   flag))))
19753
19754(defun org-end-of-subtree (&optional invisible-OK)
19755  ;; This is an exact copy of the original function, but it uses
19756  ;; `org-back-to-heading', to make it work also in invisible
19757  ;; trees.  And is uses an invisible-OK argument.
19758  ;; Under Emacs this is not needed, but the old outline.el needs this fix.
19759  (org-back-to-heading invisible-OK)
19760  (let ((first t)
19761	(level (funcall outline-level)))
19762    (while (and (not (eobp))
19763		(or first (> (funcall outline-level) level)))
19764      (setq first nil)
19765      (outline-next-heading))
19766    (if (memq (preceding-char) '(?\n ?\^M))
19767	(progn
19768	  ;; Go to end of line before heading
19769	  (forward-char -1)
19770	  (if (memq (preceding-char) '(?\n ?\^M))
19771	      ;; leave blank line before heading
19772	      (forward-char -1)))))
19773  (point))
19774
19775(defun org-show-subtree ()
19776  "Show everything after this heading at deeper levels."
19777  (outline-flag-region
19778   (point)
19779   (save-excursion
19780     (outline-end-of-subtree) (outline-next-heading) (point))
19781   nil))
19782
19783(defun org-show-entry ()
19784  "Show the body directly following this heading.
19785Show the heading too, if it is currently invisible."
19786  (interactive)
19787  (save-excursion
19788    (org-back-to-heading t)
19789    (outline-flag-region
19790     (max 1 (1- (point)))
19791     (save-excursion
19792       (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
19793       (or (match-beginning 1) (point-max)))
19794     nil)))
19795
19796(defun org-make-options-regexp (kwds)
19797  "Make a regular expression for keyword lines."
19798  (concat
19799   "^"
19800   "#?[ \t]*\\+\\("
19801   (mapconcat 'regexp-quote kwds "\\|")
19802   "\\):[ \t]*"
19803   "\\(.+\\)"))
19804
19805;; Make isearch reveal the necessary context
19806(defun org-isearch-end ()
19807  "Reveal context after isearch exits."
19808  (when isearch-success ; only if search was successful
19809    (if (featurep 'xemacs)
19810	;; Under XEmacs, the hook is run in the correct place,
19811	;; we directly show the context.
19812	(org-show-context 'isearch)
19813      ;; In Emacs the hook runs *before* restoring the overlays.
19814      ;; So we have to use a one-time post-command-hook to do this.
19815      ;; (Emacs 22 has a special variable, see function `org-mode')
19816      (unless (and (boundp 'isearch-mode-end-hook-quit)
19817		   isearch-mode-end-hook-quit)
19818	;; Only when the isearch was not quitted.
19819	(org-add-hook 'post-command-hook 'org-isearch-post-command
19820		      'append 'local)))))
19821
19822(defun org-isearch-post-command ()
19823  "Remove self from hook, and show context."
19824  (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
19825  (org-show-context 'isearch))
19826
19827;;;; Repair problems with some other packages
19828
19829;; Make `bookmark-jump' show the jump location if it was hidden.
19830(eval-after-load "bookmark"
19831  '(if (boundp 'bookmark-after-jump-hook)
19832       ;; We can use the hook
19833       (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
19834     ;; Hook not available, use advice
19835     (defadvice bookmark-jump (after org-make-visible activate)
19836       "Make the position visible."
19837       (org-bookmark-jump-unhide))))
19838
19839(defun org-bookmark-jump-unhide ()
19840  "Unhide the current position, to show the bookmark location."
19841  (and (org-mode-p)
19842       (or (org-invisible-p)
19843	   (save-excursion (goto-char (max (point-min) (1- (point))))
19844			   (org-invisible-p)))
19845       (org-show-context 'bookmark-jump)))
19846
19847;; Make session.el ignore our circular variable
19848(eval-after-load "session"
19849  '(add-to-list 'session-globals-exclude 'org-mark-ring))
19850
19851;;;; Experimental code
19852
19853
19854;;;; Finish up
19855
19856(provide 'org)
19857
19858(run-hooks 'org-load-hook)
19859
19860;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
19861;;; org.el ends here
19862
19863