emacs-diffs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Emacs-diffs] Changes to emacs/lisp/textmodes/org.el,v


From: Carsten Dominik
Subject: [Emacs-diffs] Changes to emacs/lisp/textmodes/org.el,v
Date: Wed, 06 Jun 2007 15:13:28 +0000

CVSROOT:        /sources/emacs
Module name:    emacs
Changes by:     Carsten Dominik <cdominik>      07/06/06 15:13:28

Index: org.el
===================================================================
RCS file: /sources/emacs/emacs/lisp/textmodes/org.el,v
retrieving revision 1.135
retrieving revision 1.136
diff -u -b -r1.135 -r1.136
--- org.el      22 Mar 2007 10:22:36 -0000      1.135
+++ org.el      6 Jun 2007 15:13:27 -0000       1.136
@@ -1,11 +1,11 @@
-;;;; org.el --- Outline-based notes management and organize
+;;; org.el --- Outline-based notes management and organizer
 ;; Carstens outline-mode for keeping track of everything.
 ;; Copyright (C) 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
 ;;
 ;; Author: Carsten Dominik <dominik at science dot uva dot nl>
 ;; Keywords: outlines, hypermedia, calendar, wp
 ;; Homepage: http://www.astro.uva.nl/~dominik/Tools/org/
-;; Version: 4.67d
+;; Version: 4.77
 ;;
 ;; This file is part of GNU Emacs.
 ;;
@@ -83,7 +83,7 @@
 
 ;;; Version
 
-(defvar org-version "4.67c"
+(defconst org-version "4.76"
   "The version number of the file org.el.")
 (defun org-version ()
   (interactive)
@@ -153,21 +153,13 @@
   :group 'org-startup
   :type 'boolean)
 
-(defcustom org-CUA-compatible nil
-  "Non-nil means use alternative key bindings for S-<cursor movement>.
-Org-mode used S-<cursor movement> for changing timestamps and priorities.
-S-<cursor movement> is also used for example by `CUA-mode' to select text.
-If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
-alternative bindings.  Setting this variable to t will replace the following
-keys both in Org-mode and in the Org-agenda buffer.
-
-S-RET   -> C-S-RET
-S-up    -> M-p
-S-down  -> M-n
-S-left  -> M--
-S-right -> M-+
-
-If you do not like the alternative keys, take a look at the variable
+(defcustom org-replace-disputed-keys nil
+  "Non-nil means use alternative key bindings for some keys.
+Org-mode uses S-<cursor> keys for changing timestamps and priorities.
+These keys are also used by other packages like `CUA-mode' or `windmove.el'.
+If you want to use Org-mode together with one of these other modes,
+or more generally if you would like to move some Org-mode commands to
+other keys, set this variable and configure the keys with the variable
 `org-disputed-keys'.
 
 This option is only relevant at load-time of Org-mode, and must be set
@@ -176,21 +168,47 @@
   :group 'org-startup
   :type 'boolean)
 
-(defvar org-disputed-keys
-  '((S-up     [(shift up)]      [(meta ?p)])
-    (S-down   [(shift down)]    [(meta ?n)])
-    (S-left   [(shift left)]    [(meta ?-)])
-    (S-right  [(shift right)]   [(meta ?+)])
-    (S-return [(shift return)]  [(control shift return)]))
+(if (fboundp 'defvaralias)
+    (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
+
+(defcustom org-disputed-keys
+  '(([(shift up)]              . [(meta p)])
+    ([(shift down)]            . [(meta n)])
+    ([(shift left)]            . [(meta -)])
+    ([(shift right)]           . [(meta +)])
+    ([(control shift right)]   . [(meta shift +)])
+    ([(control shift left)]    . [(meta shift -)]))
   "Keys for which Org-mode and other modes compete.
-This is an alist, cars are symbols for lookup, 1st element is the default key,
-second element will be used when `org-CUA-compatible' is t.")
+This is an alist, cars are the default keys, second element specifies
+the alternative to use when `org-replace-disputed-keys' is t.
+
+Keys can be specified in any syntax supported by `define-key'.
+The value of this option takes effect only at Org-mode's startup,
+therefore you'll have to restart Emacs to apply it after changing."
+  :group 'org-startup
+  :type 'alist)
 
 (defun org-key (key)
-  "Select a key according to `org-CUA-compatible'."
-  (nth (if org-CUA-compatible 2 1)
-       (or (assq key org-disputed-keys)
-          (error "Invalid Key %s in `org-key'" key))))
+  "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
+Or return the original if not disputed."
+  (if org-replace-disputed-keys
+      (let* ((nkey (key-description key))
+            (x (org-find-if (lambda (x)
+                              (equal (key-description (car x)) nkey))
+                            org-disputed-keys)))
+       (if x (cdr x) key))
+    key))
+
+(defun org-find-if (predicate seq)
+  (catch 'exit
+    (while seq
+      (if (funcall predicate (car seq))
+         (throw 'exit (car seq))
+       (pop seq)))))
+
+(defun org-defkey (keymap key def)
+  "Define a key, possibly translated, as returned by `org-key'."
+  (define-key keymap (org-key key) def))
 
 (defcustom org-ellipsis nil
   "The ellipsis to use in the Org-mode outline.
@@ -255,7 +273,9 @@
   :group 'org-keywords
   :type 'string)
 
-(defvar org-repeat-re "\\<REPEAT(\\([-+ 0-9dwmy]+\\))"
+(defconst org-repeat-re
+  (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
+         " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] 
[^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
   "Regular expression for specifying repeated events.
 After a match, group 1 contains the repeat expression.")
 
@@ -304,7 +324,7 @@
                    (const default))
                   (boolean)))))
 
-(defcustom org-show-following-heading '((default . t))
+(defcustom org-show-following-heading '((default . nil))
   "Non-nil means, show following heading when revealing a location.
 Org-mode often shows locations in an org-mode file which might have
 been invisible before.  When this is set, the heading following the
@@ -386,6 +406,7 @@
 white       Only in completely white lines
 whitestart  Only at the beginning of lines, before the first non-white char.
 t           Everywhere except in headlines
+exc-hl-bol  Everywhere except at the start of a headline
 If TAB is used in a place where it does not emulate TAB, the current subtree
 visibility is cycled."
   :group 'org-cycle
@@ -393,9 +414,25 @@
                 (const :tag "Only in completely white lines" white)
                 (const :tag "Before first char in a line" whitestart)
                 (const :tag "Everywhere except in headlines" t)
+                (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
                 ))
 
+(defcustom org-cycle-separator-lines 2
+  "Number of empty lines needed to keep an empty line between collapsed trees.
+If you leave an empty line between the end of a subtree and the following
+headline, this empty line is hidden when the subtree is folded.
+Org-mode will leave (exactly) one empty line visible if the number of
+empty lines is equal or larger to the number given in this variable.
+So the default 2 means, at least 2 empty lines after the end of a subtree
+are needed to produce free space between a collapsed subtree and the
+following headline.
+
+Special case: when 0, never leave empty lines in collapsed view."
+  :group 'org-cycle
+  :type 'integer)
+
 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
+                           org-cycle-show-empty-lines
                            org-optimize-window-after-visibility-change)
   "Hook that is run after `org-cycle' has changed the buffer visibility.
 The function(s) in this hook must accept a single argument which indicates
@@ -406,12 +443,20 @@
   :group 'org-cycle
   :type 'hook)
 
-
 (defgroup org-edit-structure nil
   "Options concerning structure editing in Org-mode."
   :tag "Org Edit Structure"
   :group 'org-structure)
 
+(defcustom org-special-ctrl-a nil
+  "Non-nil means `C-a' behaves specially in headlines.
+When set, `C-a' will bring back the cursor to the beginning of the
+headline text, i.e. after the stars and after a possible TODO keyword.
+When the cursor is already at that position, another `C-a' will bring
+it to the beginning of the line."
+  :group 'org-edit-structure
+  :type 'boolean)
+
 (defcustom org-odd-levels-only nil
   "Non-nil means, skip even levels and only use odd levels for the outline.
 This has the effect that two stars are being added/taken away in
@@ -783,6 +828,18 @@
   :tag "Org Table Calculation"
   :group 'org-table)
 
+(defcustom org-table-use-standard-references t
+  "Should org-mode work with table refrences like B3 instead of @3$2?
+Possible values are:
+nil     never use them
+from    accept as input, do not present for editing
+t:      accept as input and present for editing"
+  :group 'org-table-calculation
+  :type '(choice
+         (const :tag "Never, don't even check unser input for them" nil)
+         (const :tag "Always, both as user input, and when editing" t)
+         (const :tag "Convert user input, don't offer during editing" 'from)))
+
 (defcustom org-table-copy-increment t
   "Non-nil means, increment when copying current field with 
\\[org-table-copy-down]."
   :group 'org-table-calculation
@@ -815,9 +872,6 @@
   :group 'org-table-calculation
   :type 'boolean)
 
-;; FIXME this is also a variable that makes Org-mode files non-portable
-;; Maybe I should have a #+ options for constants?
-;; How about the SI/cgs issue?
 (defcustom org-table-formula-use-constants t
   "Non-nil means, interpret constants in formulas in tables.
 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
@@ -826,6 +880,8 @@
   :group 'org-table-calculation
   :type 'boolean)
 
+;; FIXME this is also a variable that makes Org-mode files non-portable
+;; Maybe I should have a #+ options for constants?
 (defcustom org-table-formula-constants nil
   "Alist with constant names and values, for use in table formulas.
 The car of each element is a name of a constant, without the `$' before it.
@@ -852,7 +908,7 @@
   :group 'org)
 
 (defvar org-link-abbrev-alist-local nil
-  "buffer-local version of `org-link-abbrev-alist', which see.
+  "Buffer-local version of `org-link-abbrev-alist', which see.
 The value of this is taken from the #+LINK lines.")
 (make-variable-buffer-local 'org-link-abbrev-alist-local)
 
@@ -1318,30 +1374,64 @@
   :tag "Org Progress"
   :group 'org-time)
 
-(defcustom org-todo-keywords '("TODO" "DONE")
-  "List of TODO entry keywords.
-\\<org-mode-map>By default, this is '(\"TODO\" \"DONE\").  The last entry in 
the list is
-considered to mean that the entry is \"done\".  All the other mean that
-action is required, and will make the entry show up in todo lists, diaries
-etc.
-The command \\[org-todo] cycles an entry through these states, and an
+(defcustom org-todo-keywords '((sequence "TODO" "DONE"))
+  "List of TODO entry keyword sequences and their interpretation.
+\\<org-mode-map>This is a list of sequences.
+
+Each sequence starts with a symbol, either `sequence' or `type',
+indicating if the keywords should be interpreted as a sequence of
+action steps, or as different types of TODO items.  The first
+keywords are states requiring action - these states will select a headline
+for inclusion into the global TODO list Org-mode produces.  If one of
+the \"keywords\" is the vertical bat \"|\" the remaining keywords
+signify that no further action is necessary.  If \"|\" is not found,
+the last keyword is treated as the only DONE state of the sequence.
+
+The command \\[org-todo] cycles an entry through these states, and one
 additional state where no keyword is present.  For details about this
-cycling, see also the variable `org-todo-interpretation'
-Changes become only effective after restarting Emacs."
+cycling, see the manual.
+
+TODO keywords and interpretation can also be set on a per-file basis with
+the special #+SEQ_TODO and #+TYP_TODO lines.
+
+For backward compatibility, this variable may also be just a list
+of keywords - in this case the interptetation (sequence or type) will be
+taken from the (otherwise obsolete) variable `org-todo-interpretation'."
   :group 'org-todo
   :group 'org-keywords
-  :type '(repeat (string :tag "Keyword")))
+  :type '(choice
+         (repeat :tag "Old syntax, just keywords"
+                 (string :tag "Keyword"))
+         (repeat :tag "New syntax"
+                 (cons
+                  (choice
+                   :tag "Interpretation"
+                   (const :tag "Sequence (cycling hits every state)" sequence)
+                   (const :tag "Type     (cycling directly to DONE)" type))
+                  (repeat
+                   (string :tag "Keyword"))))))
+
+(defvar org-todo-keywords-1 nil)
+(make-variable-buffer-local 'org-todo-keywords-1)
+(defvar org-todo-keywords-for-agenda nil)
+(defvar org-done-keywords-for-agenda nil)
+(defvar org-not-done-keywords nil)
+(make-variable-buffer-local 'org-not-done-keywords)
+(defvar org-done-keywords nil)
+(make-variable-buffer-local 'org-done-keywords)
+(defvar org-todo-heads nil)
+(make-variable-buffer-local 'org-todo-heads)
+(defvar org-todo-sets nil)
+(make-variable-buffer-local 'org-todo-sets)
+(defvar org-todo-kwd-alist nil)
+(make-variable-buffer-local 'org-todo-kwd-alist)
 
 (defcustom org-todo-interpretation 'sequence
   "Controls how TODO keywords are interpreted.
-This variable is only relevant if `org-todo-keywords' contains more than two
-states.  \\<org-mode-map>Possible values are `sequence' and `type'.
-
-When `sequence', \\[org-todo] will always switch to the next state in the
-`org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
-to state when executed several times in direct succession.  Otherwise, it
-switches directly to DONE from any state.
-See the manual for more information."
+This variable is in principle obsolete and is only used for
+backward compatibility, if the interpretation of todo keywords is
+not given already in `org-todo-keywords'.  See that variable for
+more information."
   :group 'org-todo
   :group 'org-keywords
   :type '(choice (const sequence)
@@ -1393,6 +1483,12 @@
               (const :tag "when TODO state changes" state)
               (const :tag "when clocking out" clock-out))))
 
+(defcustom org-log-done-with-time t
+  "Non-nil means, the CLOSED time stamp will contain date and time.
+When nil, only the date will be recorded."
+  :group 'org-progress
+  :type 'boolean)
+
 (defcustom org-log-note-headings
   '((done . "CLOSING NOTE %t")
     (state . "State %-12s %t")
@@ -1414,11 +1510,9 @@
                       state) string)
          (cons (const :tag "Heading when clocking out" clock-out) string)))
 
-(defcustom org-allow-auto-repeat t
-  "Non-nil means, find REPEAT cookies in entries and apply them.
-A repeat cookie looks like REPEAT(+1m) and causes deadlines and schedules
-to repeat themselves shifted by a certain amount of time, each time an
-entry is marked DONE."
+(defcustom org-log-repeat t
+  "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
+When nil, no note will be taken."
   :group 'org-todo
   :group 'org-progress
   :type 'boolean)
@@ -1428,14 +1522,21 @@
   :tag "Org Priorities"
   :group 'org-todo)
 
-(defcustom org-default-priority ?B
-  "The default priority of TODO items.
-This is the priority an item get if no explicit priority is given."
+(defcustom org-highest-priority ?A
+  "The highest priority of TODO items.  A character like ?A, ?B etc.
+Must have a smaller ASCII number than `org-lowest-priority'."
   :group 'org-priorities
   :type 'character)
 
 (defcustom org-lowest-priority ?C
-  "The lowest priority of TODO items.  A character like ?A, ?B etc."
+  "The lowest priority of TODO items.  A character like ?A, ?B etc.
+Must have a larger ASCII number than `org-highest-priority'."
+  :group 'org-priorities
+  :type 'character)
+
+(defcustom org-default-priority ?B
+  "The default priority of TODO items.
+This is the priority an item get if no explicit priority is given."
   :group 'org-priorities
   :type 'character)
 
@@ -1612,7 +1713,7 @@
   "Variable used by org files to set a category for agenda display.
 Such files should use a file variable to set it, for example
 
-   -*- mode: org; org-category: \"ELisp\"
+#   -*- mode: org; org-category: \"ELisp\"
 
 or contain a special line
 
@@ -1654,17 +1755,75 @@
   :group 'org-agenda
   :type 'sexp)
 
+(defgroup org-agenda-export nil
+ "Options concerning exporting agenda views in Org-mode."
+ :tag "Org Agenda Export"
+ :group 'org-agenda)
+
+(defcustom org-agenda-with-colors t
+  "Non-nil means, use colors in agenda views."
+  :group 'org-agenda-export
+  :type 'boolean)
+
+(defcustom org-agenda-exporter-settings nil
+  "Alist of variable/value pairs that should be active during agenda export.
+This is a good place to set uptions for ps-print and for htmlize."
+  :group 'org-agenda-export
+  :type '(repeat
+         (list
+          (variable)
+          (sexp :tag "Value"))))
+
+(defcustom org-agenda-export-html-style ""
+  "The style specification for exported HTML Agenda files.
+If this variable contains a string, it will replace the default <style>
+section as produced by `htmlize'.
+Since there are different ways of setting style information, this variable
+needs to contain the full HTML structure to provide a style, including the
+surrounding HTML tags.  The style specifications should include definitions
+the fonts used by the agenda, here is an example:
+
+   <style type=\"text/css\">
+       p { font-weight: normal; color: gray; }
+       .org-agenda-structure {
+          font-size: 110%;
+          color: #003399;
+          font-weight: 600;
+       }
+       .org-todo {
+          color: #cc6666;Week-agenda:
+          font-weight: bold;
+       }
+       .org-done {
+          color: #339933;
+       }
+       .title { text-align: center; }
+       .todo, .deadline { color: red; }
+       .done { color: green; }
+    </style>
+
+or, if you want to keep the style in a file,
+
+   <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
+
+As the value of this option simply gets inserted into the HTML <head> header,
+you can \"misuse\" it to also add other text to the header.  However,
+<style>...</style> is required, if not present the variable will be ignored."
+  :group 'org-agenda-export
+  :group 'org-export-html
+  :type 'string)
+
 (defgroup org-agenda-custom-commands nil
  "Options concerning agenda views in Org-mode."
  :tag "Org Agenda Custom Commands"
  :group 'org-agenda)
 
-(defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
+(defcustom org-agenda-custom-commands nil
   "Custom commands for the agenda.
 These commands will be offered on the splash screen displayed by the
 agenda dispatcher \\[org-agenda].  Each entry is a list like this:
 
-   (key type match options)
+   (key type match options files)
 
 key     The key (a single char as a string) to be associated with the command.
 type    The command type, any of the following symbols:
@@ -1680,11 +1839,16 @@
          - a regular expression for occur searches
 options  A list of option setttings, similar to that in a let form, so like
          this: ((opt1 val1) (opt2 val2) ...)
+files    A list of files file to write the produced agenda buffer to
+         with the command `org-store-agenda-views'.
+         If a file name ends in \".html\", an HTML version of the buffer
+         is written out.  If it ends in \".ps\", a postscript version is
+         produced.  Otherwide, only the plain text is written to the file.
 
 You can also define a set of commands, to create a composite agenda buffer.
 In this case, an entry looks like this:
 
-  (key desc (cmd1 cmd2 ...) general-options)
+  (key desc (cmd1 cmd2 ...) general-options file)
 
 where
 
@@ -1695,19 +1859,22 @@
        (agenda)
        (alltodo)
        (stuck)
-       (todo \"match\" options)
-       (tags \"match\" options )
-       (tags-todo \"match\" options)
+       (todo \"match\" options files)
+       (tags \"match\" options files)
+       (tags-todo \"match\" options files)
 
 Each command can carry a list of options, and another set of options can be
 given for the whole set of commands.  Individual command options take
 precedence over the general options."
   :group 'org-agenda-custom-commands
   :type '(repeat
-         (choice
+         (choice :value ("a" tags "" nil)
           (list :tag "Single command"
                 (string :tag "Key")
                 (choice
+                 (const :tag "Agenda" agenda)
+                 (const :tag "TODO list" alltodo)
+                 (const :tag "Stuck projects" stuck)
                  (const :tag "Tags search (all agenda files)" tags)
                  (const :tag "Tags search of TODO entries (all agenda files)" 
tags-todo)
                  (const :tag "TODO keyword search (all agenda files)" todo)
@@ -1717,7 +1884,8 @@
                  (symbol :tag "Other, user-defined function"))
                 (string :tag "Match")
                 (repeat :tag "Local options"
-                        (list (variable :tag "Option") (sexp :tag "Value"))))
+                        (list (variable :tag "Option") (sexp :tag "Value")))
+                (option (repeat :tag "Export" (file :tag "Export to"))))
           (list :tag "Command series, all agenda files"
                 (string :tag "Key")
                 (string :tag "Description")
@@ -1756,20 +1924,24 @@
 
                 (repeat :tag "General options"
                         (list (variable :tag "Option")
-                              (sexp :tag "Value")))))))
+                              (sexp :tag "Value")))
+                (option (repeat :tag "Export" (file :tag "Export to")))))))
 
 (defcustom org-stuck-projects
-  '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil)
+  '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
   "How to identify stuck projects.
-This is a list of three items:
+This is a list of four items:
 1. A tags/todo matcher string that is used to identify a project.
-   The entire tree below a headline matched by this is considered a project.
-2. A list of TODO keywords itentifying non-stuck projects.
+   The entire tree below a headline matched by this is considered one project.
+2. A list of TODO keywords identifying non-stuck projects.
    If the project subtree contains any headline with one of these todo
-   keywords, the project is consitered to be not stuck.
+   keywords, the project is considered to be not stuck.  If you specify
+   \"*\" as a keyword, any TODO keyword will mark the project unstuck.
 3. A list of tags identifying non-stuck projects.
    If the project subtree contains any headline with one of these tags,
-   the project is consitered to be not stuck.
+   the project is considered to be not stuck.  If you specify \"*\" as
+   a tag, any tag will mark the project unstuck.
+4. An arbitrary regular expression matching non-stuck projects.
 
 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
 or `C-c a #' to produce the list."
@@ -1777,7 +1949,8 @@
   :type '(list
          (string :tag "Tags/TODO match to identify a project")
          (repeat :tag "Projects are *not* stuck if they have an entry with 
TODO keyword any of" (string))
-         (repeat :tag "Projects are *not* stuck if they have an entry with TAG 
being any of" (string))))
+         (repeat :tag "Projects are *not* stuck if they have an entry with TAG 
being any of" (string))
+         (regexp :tag "Projects are *not* stuck if this regexp matches\ninside 
the subtree")))
 
 
 (defgroup org-agenda-skip nil
@@ -1815,6 +1988,14 @@
   :group 'org-agenda-skip
   :type 'boolean)
 
+(defcustom org-agenda-skip-deadline-if-done nil
+  "Non-nil means don't show deadines when the corresponding item is done.
+When nil, the deadline is still shown and should give you a happy feeling.
+
+This is relevant for the daily/weekly agenda."
+  :group 'org-agenda-skip
+  :type 'boolean)
+
 (defcustom org-timeline-show-empty-dates 3
   "Non-nil means, `org-timeline' also shows dates without an entry.
 When nil, only the days which actually have entries are shown.
@@ -1846,7 +2027,7 @@
   :type 'boolean)
 
 (defcustom org-agenda-start-with-follow-mode nil
-  "The initial value of follwo-mode in a newly created agenda window."
+  "The initial value of follow-mode in a newly created agenda window."
   :group 'org-agenda-startup
   :type 'boolean)
 
@@ -2006,7 +2187,7 @@
   (defcustom org-agenda-sorting-strategy
     '((agenda time-up category-keep priority-down)
       (todo category-keep priority-down)
-      (tags category-keep))
+      (tags category-keep priority-down))
     "Sorting structure for the agenda items of a single day.
 This is a list of symbols which will be used in sequence to determine
 if an entry should be listed before another entry.  The following
@@ -2113,7 +2294,7 @@
   (setq org-agenda-prefix-format \"  %-11:c% s\")
 
 See also the variables `org-agenda-remove-times-when-in-prefix' and
-`org-agenda-remove-tags-when-in-prefix'."
+`org-agenda-remove-tags'."
   :type '(choice
          (string :tag "General format")
          (list :greedy t :tag "View dependent"
@@ -2144,7 +2325,7 @@
          (const :tag "Never" nil)
          (const :tag "When at beginning of entry" beg)))
 
-(defcustom org-agenda-remove-tags-when-in-prefix nil
+(defcustom org-agenda-remove-tags nil
   "Non-nil means, remove the tags from the headline copy in the agenda.
 When this is the symbol `prefix', only remove tags when
 `org-agenda-prefix-format' contains a `%T' specifier."
@@ -2154,6 +2335,10 @@
          (const :tag "Never" nil)
          (const :tag "When prefix format contains %T" prefix)))
 
+(if (fboundp 'defvaralias)
+    (defvaralias 'org-agenda-remove-tags-when-in-prefix
+      'org-agenda-remove-tags))
+
 (defcustom org-agenda-align-tags-to-column 65
   "Shift tags in agenda items to this column."
   :group 'org-agenda-prefix
@@ -2165,13 +2350,18 @@
   :group 'org)
 
 (defcustom org-format-latex-options
-  '(:foreground "Black" :background "Transparent" :scale 1.0
+  '(:foreground default :background default :scale 1.0
+    :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
                :matchers ("begin" "$" "$$" "\\(" "\\["))
   "Options for creating images from LaTeX fragments.
 This is a property list with the following properties:
-:foreground  the foreground color, for example \"Black\".
+:foreground  the foreground color for images embedded in emacs, e.g. \"Black\".
+             `default' means use the forground of the default face.
 :background  the background color, or \"Transparent\".
+             `default' means use the background of the default face.
 :scale       a scaling factor for the size of the images
+:html-foreground, :html-background, :html-scale
+             The same numbers for HTML export.
 :matchers    a list indicating which matchers should be used to
              find LaTeX fragments.  Valid members of this list are:
              \"begin\"  find environments
@@ -2182,6 +2372,18 @@
   :group 'org-latex
   :type 'plist)
 
+(defcustom org-format-latex-header "\\documentclass{article}
+\\usepackage{fullpage}         % do not remove
+\\usepackage{amssymb}
+\\usepackage[usenames]{color}
+\\usepackage{amsmath}
+\\usepackage{latexsym}
+\\usepackage[mathscr]{eucal}
+\\pagestyle{empty}             % do not remove"
+  "The document header used for processing LaTeX fragments."
+  :group 'org-latex
+  :type 'string)
+
 (defgroup org-export nil
   "Options for exporting org-listings."
   :tag "Org Export"
@@ -2237,6 +2439,12 @@
   :group 'org-export-general
   :type 'string)
 
+(defcustom org-export-skip-text-before-1st-heading t
+  "Non-nil means, skip all text before the first headline when exporting.
+When nil, that text is exported as well."
+  :group 'org-export-general
+  :type 'boolean)
+
 (defcustom org-export-headline-levels 3
   "The last level which is still exported as a headline.
 Inferior levels will produce itemize lists when exported.
@@ -2354,12 +2562,19 @@
  x_{i^2} or   x^(2-i)    braces or parenthesis do grouping.
 
 Still, ambiguity is possible - so when in doubt use {} to enclose the
-sub/superscript.
+sub/superscript.  If you set this variable to the symbol `{}',
+the braces are *required* in order to trigger interpretations as
+sub/superscript.  This can be helpful in documents that need \"_\"
+frequently in plain text.
+
 Not all export backends support this, but HTML does.
 
 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
   :group 'org-export-translation
-  :type 'boolean)
+  :type '(choice
+         (const :tag "Always interpret" t)
+         (const :tag "Only with braces" {})
+         (const :tag "Never interpret" nil)))
 
 (defcustom org-export-with-TeX-macros t
   "Non-nil means, interpret simple TeX-like macros when exporting.
@@ -2534,6 +2749,7 @@
   :group 'org-export-html
   :type 'string)
 
+
 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
   "Format for typesetting the document title in HTML export."
   :group 'org-export-html
@@ -2579,12 +2795,24 @@
 
 (defcustom org-export-html-table-tag
   "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" 
frame=\"hsides\">"
-  "The HTML tag used to start a table.
+  "The HTML tag that is used to start a table.
 This must be a <table> tag, but you may change the options like
 borders and spacing."
   :group 'org-export-html
   :type 'string)
 
+(defcustom org-export-table-header-tags '("<th>" . "</th>")
+  "The opening tag for table header fields.
+This is customizable so that alignment options can be specified."
+  :group 'org-export-tables
+  :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
+
+(defcustom org-export-table-data-tags '("<td>" . "</td>")
+  "The opening tag for table data fields.
+This is customizable so that alignment options can be specified."
+  :group 'org-export-tables
+  :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
+
 (defcustom org-export-html-with-timestamp nil
   "If non-nil, write `org-export-html-html-helper-timestamp'
 into the exported HTML text.  Otherwise, the buffer will just be saved
@@ -2618,6 +2846,12 @@
          (const :tag "Unfinished" t)
          (const :tag "All" all)))
 
+(defcustom org-icalendar-include-sexps t
+  "Non-nil means, export to iCalendar files should also cover sexp entries.
+These are entries like in the diary, but directly in an Org-mode file."
+  :group 'org-export-icalendar
+  :type 'boolean)
+
 (defcustom org-icalendar-combined-name "OrgMode"
   "Calendar name for the combined iCalendar representing all agenda files."
   :group 'org-export-icalendar
@@ -2690,8 +2924,6 @@
          (setq markers (concat (replace-match "" t t markers) "^")))
       (if (string-match "-" markers)
          (setq markers (concat (replace-match "" t t markers) "-")))
-;      (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body 
"*?")))
-;      (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\\(?:\n?" 
body "*?\\)?")))
       (if (> nl 0)
           (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
                               (int-to-string nl) "\\}")))
@@ -2701,15 +2933,15 @@
                    "\\("
                    "\\([" markers "]\\)"
                    "\\("
-                   "[^" border markers "]"
+                   "[^" border (if (and nil stacked) markers) "]"
                    body1
-                   "[^" border markers "]"
+                   "[^" border (if (and nil stacked) markers) "]"
                    "\\)"
                    "\\3\\)"
                    "\\([" post (if stacked markers) "]\\|$\\)")))))
 
 (defcustom org-emphasis-regexp-components
-  '(" \t('\"" " \t.,?;'\")" " \t\r\n," "." 1 nil)
+  '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1 nil)
   "Components used to build the reqular expression for emphasis.
 This is a list with 6 entries.  Terminology:  In an emphasis string
 like \" *strong word* \", we call the initial space PREMATCH, the final
@@ -2719,8 +2951,7 @@
 
 pre          Chars allowed as prematch.  Beginning of line will be allowed too.
 post         Chars allowed as postmatch.  End of line will be allowed too.
-border       The chars *forbidden* as border characters.  In addition to the
-             characters given here, all marker characters are forbidden too.
+border       The chars *forbidden* as border characters.
 body-regexp  A regexp like \".\" to match a body character.  Don't use
              non-shy groups here, and don't allow newline here.
 newline      The maximum number of newlines allowed in an emphasis exp.
@@ -2745,11 +2976,11 @@
     ("_" underline "<u>" "</u>")
     ("=" shadow "<code>" "</code>")
     ("+" (:strike-through t) "<del>" "</del>")
-)
+    )
 "Special syntax for emphasized text.
 Text starting and ending with a special character will be emphasized, for
 example *bold*, _underlined_ and /italic/.  This variable sets the marker
-characters, the face to bbe used by font-lock for highlighting in Org-mode
+characters, the face to be used by font-lock for highlighting in Org-mode
 Emacs buffers, and the HTML tags to be used for this.
 Use customize to modify this, or restart Emacs after changing it."
   :group 'org-font-lock
@@ -2894,15 +3125,6 @@
   "Face for deadlines and TODO keywords."
   :group 'org-faces)
 
-(defface org-headline-done ;; font-lock-string-face
-  (org-compatible-face
-   '((((class color) (min-colors 16) (background light)) (:foreground 
"RosyBrown"))
-     (((class color) (min-colors 16) (background dark)) (:foreground 
"LightSalmon"))
-     (((class color) (min-colors 8)  (background light)) (:bold nil))))
-  "Face used to indicate that a headline is DONE.
-This face is only used if `org-fontify-done-headline' is set."
-  :group 'org-faces)
-
 (defface org-archived    ; similar to shadow
   (org-compatible-face
    '((((class color grayscale) (min-colors 88) (background light))
@@ -2930,6 +3152,13 @@
   "Face for links."
   :group 'org-faces)
 
+(defface org-sexp-date
+  '((((class color) (background light)) (:foreground "Purple"))
+    (((class color) (background dark)) (:foreground "Cyan"))
+    (t (:underline t)))
+  "Face for links."
+  :group 'org-faces)
+
 (defface org-tag
   '((t (:bold t)))
   "Face for tags."
@@ -2951,7 +3180,17 @@
      (((class color) (min-colors 16) (background dark)) (:foreground 
"PaleGreen" :bold t))
      (((class color) (min-colors 8)) (:foreground "green"))
      (t (:bold t))))
-  "Face used for DONE."
+  "Face used for todo keywords that indicate DONE items."
+  :group 'org-faces)
+
+(defface org-headline-done ;; font-lock-string-face
+  (org-compatible-face
+   '((((class color) (min-colors 16) (background light)) (:foreground 
"RosyBrown"))
+     (((class color) (min-colors 16) (background dark)) (:foreground 
"LightSalmon"))
+     (((class color) (min-colors 8)  (background light)) (:bold nil))))
+  "Face used to indicate that a headline is DONE.
+This face is only used if `org-fontify-done-headline' is set.  If applies
+to the part of the headline after the DONE keyword."
   :group 'org-faces)
 
 (defface org-table ;; font-lock-function-name-face
@@ -2975,6 +3214,17 @@
   "Face for formulas."
   :group 'org-faces)
 
+(defface org-agenda-structure ;; font-lock-function-name-face
+  (org-compatible-face
+   '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
+     (((class color) (min-colors 88) (background dark)) (:foreground 
"LightSkyBlue"))
+     (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
+     (((class color) (min-colors 16) (background dark)) (:foreground 
"LightSkyBlue"))
+     (((class color) (min-colors 8)) (:foreground "blue" :bold t))
+     (t (:bold t))))
+  "Face used in agenda for captions and dates."
+  :group 'org-faces)
+
 (defface org-scheduled-today
   (org-compatible-face
    '((((class color) (min-colors 88) (background light)) (:foreground 
"DarkGreen"))
@@ -3021,9 +3271,6 @@
 
 ;;; Variables for pre-computed regular expressions, all buffer local
 
-(defvar org-done-string nil
-  "The last string in `org-todo-keywords', indicating an item is DONE.")
-(make-variable-buffer-local 'org-done-string)
 (defvar org-todo-regexp nil
   "Matches any of the TODO state keywords.")
 (make-variable-buffer-local 'org-todo-regexp)
@@ -3043,12 +3290,6 @@
 (defvar org-looking-at-done-regexp nil
   "Matches the DONE keyword a point.")
 (make-variable-buffer-local 'org-looking-at-done-regexp)
-(defvar org-todo-kwd-priority-p nil
-  "Do TODO items have priorities?")
-(make-variable-buffer-local 'org-todo-kwd-priority-p)
-(defvar org-todo-kwd-max-priority nil
-  "Maximum priority of TODO items.")
-(make-variable-buffer-local 'org-todo-kwd-max-priority)
 (defvar org-ds-keyword-length 12
   "Maximum length of the Deadline and SCHEDULED keywords.")
 (make-variable-buffer-local 'org-ds-keyword-length)
@@ -3080,6 +3321,9 @@
 (defvar org-maybe-keyword-time-regexp nil
   "Matches a timestamp, possibly preceeded by a keyword.")
 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
+(defvar org-planning-or-clock-line-re nil
+  "Matches a line with planning or clock info.")
+(make-variable-buffer-local 'org-planning-or-clock-line-re)
 
 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
                                   rear-nonsticky t mouse-map t fontified t)
@@ -3102,6 +3346,12 @@
        ((assoc key option) (cdr (assoc key option)))
        (t (cdr (assq 'default option)))))
 
+(defsubst org-inhibit-invisibility ()
+  "Modified `buffer-invisibility-spec' for Emacs 21.
+Some ops with invisible text do not work correctly on Emacs 21.  For these
+we turn off invisibility temporarily.  Use this in a `let' form."
+  (if (< emacs-major-version 22) nil buffer-invisibility-spec))
+
 (defsubst org-set-local (var value)
   "Make VAR local in current buffer and set it to VALUE."
   (set (make-variable-buffer-local var) value))
@@ -3139,7 +3389,11 @@
     ("nologging" org-log-done nil)
     ("lognotedone" org-log-done done push)
     ("lognotestate" org-log-done state push)
-    ("lognoteclock-out" org-log-done clock-out push))
+    ("lognoteclock-out" org-log-done clock-out push)
+    ("logrepeat" org-log-repeat t)
+    ("nologrepeat" org-log-repeat nil)
+    ("constcgs" constants-unit-system cgs)
+    ("constSI" constants-unit-system SI))
   "Variable associated with STARTUP options for org-mode.
 Each element is a list of three items: The startup options as written
 in the #+STARTUP line, the corresponding variable, and the value to
@@ -3149,11 +3403,16 @@
 (defun org-set-regexps-and-options ()
   "Precompute regular expressions for current buffer."
   (when (org-mode-p)
+    (org-set-local 'org-todo-kwd-alist nil)
+    (org-set-local 'org-todo-keywords-1 nil)
+    (org-set-local 'org-done-keywords nil)
+    (org-set-local 'org-todo-heads nil)
+    (org-set-local 'org-todo-sets nil)
     (let ((re (org-make-options-regexp
               '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
-                "STARTUP" "ARCHIVE" "TAGS" "LINK")))
+                "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES")))
          (splitre "[ \t]+")
-         kwds int key value cat arch tags links)
+         kwds key value cat arch tags links hw dws tail sep kws1 prio)
       (save-excursion
        (save-restriction
          (widen)
@@ -3166,14 +3425,9 @@
                  (setq value (replace-match "" t t value)))
              (setq cat (intern value)))
             ((equal key "SEQ_TODO")
-             (setq int 'sequence
-                   kwds (append kwds (org-split-string value splitre))))
-            ((equal key "PRI_TODO")
-             (setq int 'priority
-                   kwds (append kwds (org-split-string value splitre))))
+             (push (cons 'sequence (org-split-string value splitre)) kwds))
             ((equal key "TYP_TODO")
-             (setq int 'type
-                   kwds (append kwds (org-split-string value splitre))))
+             (push (cons 'type (org-split-string value splitre)) kwds))
             ((equal key "TAGS")
              (setq tags (append tags (org-split-string value splitre))))
             ((equal key "LINK")
@@ -3181,17 +3435,20 @@
                (push (cons (match-string 1 value)
                            (org-trim (match-string 2 value)))
                      links)))
+            ((equal key "PRIORITIES")
+             (setq prio (org-split-string value " +")))
             ((equal key "STARTUP")
              (let ((opts (org-split-string value splitre))
                    l var val)
-               (while (setq l (assoc (pop opts) org-startup-options))
+               (while (setq l (pop opts))
+                 (when (setq l (assoc l org-startup-options))
                  (setq var (nth 1 l) val (nth 2 l))
                  (if (not (nth 3 l))
                      (set (make-local-variable var) val)
                    (if (not (listp (symbol-value var)))
                        (set (make-local-variable var) nil))
                    (set (make-local-variable var) (symbol-value var))
-                   (add-to-list var val)))))
+                     (add-to-list var val))))))
             ((equal key "ARCHIVE")
              (string-match " *$" value)
              (setq arch (replace-match "" t t value))
@@ -3199,10 +3456,38 @@
                                      '(face t fontified t) arch)))
            )))
       (and cat (org-set-local 'org-category cat))
-      (and kwds (org-set-local 'org-todo-keywords kwds))
+      (when prio
+       (if (< (length prio) 3) (setq prio '("A" "C" "B")))
+       (setq prio (mapcar 'string-to-char prio))
+       (org-set-local 'org-highest-priority (nth 0 prio))
+       (org-set-local 'org-lowest-priority  (nth 1 prio))
+       (org-set-local 'org-default-priority (nth 2 prio)))
       (and arch (org-set-local 'org-archive-location arch))
-      (and int (org-set-local 'org-todo-interpretation int))
       (and links (setq org-link-abbrev-alist-local (nreverse links)))
+      ;; Process the TODO keywords
+      (unless kwds
+       ;; Use the global values as if they had been given locally.
+       (setq kwds (default-value 'org-todo-keywords))
+       (if (stringp (car kwds))
+           (setq kwds (list (cons org-todo-interpretation
+                                  (default-value 'org-todo-keywords)))))
+       (setq kwds (reverse kwds)))
+      (setq kwds (nreverse kwds))
+      (let (inter kws)
+       (while (setq kws (pop kwds))
+         (setq inter (pop kws) sep (member "|" kws)
+               kws1 (delete "|" (copy-sequence kws))
+               hw (car kws1)
+               dws (if sep (cdr sep) (last kws1))
+               tail (list inter hw (car dws) (org-last dws)))
+         (add-to-list 'org-todo-heads hw 'append)
+         (push kws1 org-todo-sets)
+         (setq org-done-keywords (append org-done-keywords dws nil))
+         (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
+         (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
+       (setq org-todo-sets (nreverse org-todo-sets)
+             org-todo-kwd-alist (nreverse org-todo-kwd-alist)))
+      ;; Process the tags.
       (when tags
        (let (e tgs)
          (while (setq e (pop tags))
@@ -3221,32 +3506,35 @@
                (push e org-tag-alist))))))
 
     ;; Compute the regular expressions and other local variables
-    (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
-         org-todo-kwd-max-priority (1- (length org-todo-keywords))
-         org-ds-keyword-length (+ 2 (max (length org-deadline-string)
+    (if (not org-done-keywords)
+       (setq org-done-keywords (list (org-last org-todo-keywords-1))))
+    (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
                                          (length org-scheduled-string)))
-         org-done-string
-         (nth (1- (length org-todo-keywords)) org-todo-keywords)
+         org-not-done-keywords
+         (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
          org-todo-regexp
-         (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
+         (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
                                      "\\|") "\\)\\>")
          org-not-done-regexp
          (concat "\\<\\("
-                 (mapconcat 'regexp-quote
-                            (nreverse (cdr (reverse org-todo-keywords)))
-                            "\\|")
+                 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
                  "\\)\\>")
          org-todo-line-regexp
          (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
-                 (mapconcat 'regexp-quote org-todo-keywords "\\|")
+                 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
                  "\\)\\>\\)? *\\(.*\\)")
          org-nl-done-regexp
-         (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
+         (concat "[\r\n]\\*+[ \t]+"
+                 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
+                 "\\)" "\\>")
          org-todo-line-tags-regexp
          (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
-                 (mapconcat 'regexp-quote org-todo-keywords "\\|")
+                 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
                  "\\)\\>\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:address@hidden:[ 
\t]*\\)?$\\)")
-         org-looking-at-done-regexp (concat "^" org-done-string "\\>")
+         org-looking-at-done-regexp
+         (concat "^" "\\(?:"
+                 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
+                 "\\>")
          org-deadline-regexp (concat "\\<" org-deadline-string)
          org-deadline-time-regexp
          (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
@@ -3274,7 +3562,12 @@
                  "\\|" org-deadline-string
                  "\\|" org-closed-string
                  "\\|" org-clock-string "\\)\\)?"
-                 " 
*\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
+                 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} 
[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
+         org-planning-or-clock-line-re
+         (concat "\\(?:^[ \t]*\\(" org-scheduled-string
+                 "\\|" org-deadline-string
+                 "\\|" org-closed-string "\\|" org-clock-string "\\)\\>\\)")
+         )
 
     (org-set-font-lock-defaults)))
 
@@ -3325,6 +3618,7 @@
 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
 (defvar initial)    ; from remember.el, dynamically scoped in `remember-mode'
 (defvar org-latex-regexps)
+(defvar constants-unit-system)
 
 (defvar original-date) ; dynamically scoped in calendar.el does scope this
 
@@ -3394,6 +3688,7 @@
     (overlay-get ovl prop)))
 (defun org-overlays-at (pos)
   (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
+;; FIXME: this is currently not used
 (defun org-overlays-in (&optional start end)
   (if (featurep 'xemacs)
       (extent-list nil start end)
@@ -3402,6 +3697,7 @@
   (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
 (defun org-overlay-end (o)
   (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
+;; FIXME: this is currently not used
 (defun org-find-overlays (prop &optional pos delete)
   "Find all overlays specifying PROP at POS or point.
 If DELETE is non-nil, delete all those overlays."
@@ -3455,6 +3751,7 @@
        (setq buffer-invisibility-spec
              (delete arg buffer-invisibility-spec)))))
 
+;; FIXME: this is currently not used
 (defun org-in-invisibility-spec-p (arg)
   "Is ARG a member of `buffer-invisibility-spec'?"
   (if (consp buffer-invisibility-spec)
@@ -3477,6 +3774,7 @@
 (defvar org-mode-hook nil)
 (defvar org-inhibit-startup nil)        ; Dynamically-scoped param.
 (defvar org-agenda-keep-modes nil)      ; Dynamically-scoped param.
+(defvar org-table-buffer-is-an nil)
 
 
 ;;;###autoload
@@ -3521,7 +3819,6 @@
   (when (featurep 'xemacs)
     (org-set-local 'line-move-ignore-invisible t))
   (setq outline-regexp "\\*+")
-  ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
   (setq outline-level 'org-outline-level)
   (when (and org-ellipsis (stringp org-ellipsis)
              (fboundp 'set-display-table-slot) (boundp 'buffer-display-table))
@@ -3534,6 +3831,7 @@
   ;; Calc embedded
   (org-set-local 'calc-embedded-open-mode "# ")
   (modify-syntax-entry ?# "<")
+  (modify-syntax-entry ?@ "w")
   (if org-startup-truncated (setq truncate-lines t))
   (org-set-local 'font-lock-unfontify-region-function
                 'org-unfontify-region)
@@ -3545,6 +3843,7 @@
   (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
   ;; Paragraphs and auto-filling
   (org-set-autofill-regexps)
+  (setq indent-line-function 'org-indent-line-function)
   (org-update-radio-target-regexp)
 
   ;; Comment characters
@@ -3564,7 +3863,7 @@
   (if (and org-insert-mode-line-in-empty-file
           (interactive-p)
           (= (point-min) (point-max)))
-      (insert "    -*- mode: org -*-\n\n"))
+      (insert "#    -*- mode: org -*-\n\n"))
 
   (unless org-inhibit-startup
     (when org-startup-align-all-tables
@@ -3578,6 +3877,8 @@
       (let ((this-command 'org-cycle) (last-command 'org-cycle))
        (org-cycle '(4)) (org-cycle '(4)))))))
 
+(put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
+
 (defsubst org-call-with-arg (command arg)
   "Call COMMAND interactively, but pretend prefix are was ARG."
   (let ((current-prefix-arg arg)) (call-interactively command)))
@@ -3610,23 +3911,23 @@
 ;;;; Font-Lock stuff, including the activators
 
 (defvar org-mouse-map (make-sparse-keymap))
-(define-key org-mouse-map
+(org-defkey org-mouse-map
   (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
-(define-key org-mouse-map
+(org-defkey org-mouse-map
   (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
 (when org-mouse-1-follows-link
-  (define-key org-mouse-map [follow-link] 'mouse-face))
+  (org-defkey org-mouse-map [follow-link] 'mouse-face))
 (when org-tab-follows-link
-  (define-key org-mouse-map [(tab)] 'org-open-at-point)
-  (define-key org-mouse-map "\C-i" 'org-open-at-point))
+  (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
+  (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
 (when org-return-follows-link
-  (define-key org-mouse-map [(return)] 'org-open-at-point)
-  (define-key org-mouse-map "\C-m" 'org-open-at-point))
+  (org-defkey org-mouse-map [(return)] 'org-open-at-point)
+  (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
 
 (require 'font-lock)
 
 (defconst org-non-link-chars "]\t\n\r<>")
-(defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
+(defconst org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" 
"vm"
                           "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
 (defconst org-link-re-with-space
   (concat
@@ -3681,19 +3982,15 @@
          org-plain-link-re "\\)")
   "Regular expression matching any link.")       
 
-(defconst org-ts-lengths
-  (cons (length (format-time-string (car org-time-stamp-formats)))
-       (length (format-time-string (cdr org-time-stamp-formats))))
-  "This holds the lengths of the two different time formats.")
-(defconst org-ts-regexp 
"<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
+(defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} 
[^\r\n>]*?\\)>"
   "Regular expression for fast time stamp matching.")
-(defconst org-ts-regexp-both 
"[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
+(defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} 
[^\r\n>]*?\\)[]>]"
   "Regular expression for fast time stamp matching.")
-(defconst org-ts-regexp1 
"\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
+(defconst org-ts-regexp1 
"\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) 
\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
   "Regular expression matching time strings for analysis.")
-(defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
+(defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,6\\}>")
   "Regular expression matching time stamps, with groups.")
-(defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
+(defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,6\\}[]>]")
   "Regular expression matching time stamps (also [..]), with groups.")
 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
   "Regular expression matching a time stamp range.")
@@ -3712,27 +4009,87 @@
 
 (defun org-do-emphasis-faces (limit)
   "Run through the buffer and add overlays to links."
-  (if (re-search-forward org-emph-re limit t)
+  (let (rtn)
+    (while (and (not rtn) (re-search-forward org-emph-re limit t))
+      (if (not (= (char-after (match-beginning 3))
+                 (char-after (match-beginning 4))))
       (progn
+           (setq rtn t)
        (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
                                         'face
                                         (nth 1 (assoc (match-string 3)
                                                       org-emphasis-alist)))
        (add-text-properties (match-beginning 2) (match-end 2)
                             '(font-lock-multiline t))
-       (backward-char 1)
-       t)))
+           (backward-char 1))))
+    rtn))
+
+(defun org-emphasize (&optional char)
+  "Insert or change an emphasis, i.e. a font like bold or italic.
+If there is an active region, change that region to a new emphasis.
+If there is no region, just insert the marker characters and position
+the cursor between them.
+CHAR should be either the marker character, or the first character of the
+HTML tag associated with that emphasis.  If CHAR is a space, the means
+to remove the emphasis of the selected region.
+If char is not given (for example in an interactive call) it
+will be prompted for."
+  (interactive)
+  (let ((eal org-emphasis-alist) e det
+       (erc org-emphasis-regexp-components)
+       (prompt "")
+       (string "") beg end move tag c s)
+    (if (org-region-active-p)
+       (setq beg (region-beginning) end (region-end)
+             string (buffer-substring beg end))
+      (setq move t))
+
+    (while (setq e (pop eal))
+      (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
+           c (aref tag 0))
+      (push (cons c (string-to-char (car e))) det)
+      (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
+                                         (substring tag 1)))))
+    (unless char
+      (message "%s" (concat "Emphasis marker or tag:" prompt))
+      (setq char (read-char-exclusive)))
+    (setq char (or (cdr (assoc char det)) char))
+    (if (equal char ?\ )
+       (setq s "" move nil)
+      (unless (assoc (char-to-string char) org-emphasis-alist)
+       (error "No such emphasis marker: \"%c\"" char))
+      (setq s (char-to-string char)))
+    (while (and (> (length string) 1)
+               (equal (substring string 0 1) (substring string -1))
+               (assoc (substring string 0 1) org-emphasis-alist))
+      (setq string (substring string 1 -1)))
+    (setq string (concat s string s))
+    (if beg (delete-region beg end))
+    (unless (or (bolp)
+               (string-match (concat "[" (nth 0 erc) "\n]")
+                             (char-to-string (char-before (point)))))
+      (insert " "))
+    (unless (string-match (concat "[" (nth 1 erc) "\n]")
+                         (char-to-string (char-after (point))))
+      (insert " ") (backward-char 1))
+    (insert string)
+    (and move (backward-char 1))))
 
 (defun org-activate-plain-links (limit)
   "Run through the buffer and add overlays to links."
-  (if (re-search-forward org-plain-link-re limit t)
-      (progn
+  (catch 'exit
+    (let (f)
+      (while (re-search-forward org-plain-link-re limit t)
+       (setq f (get-text-property (match-beginning 0) 'face))
+       (if (or (eq f 'org-tag)
+               (and (listp f) (memq 'org-tag f)))
+           nil
        (add-text-properties (match-beginning 0) (match-end 0)
                             (list 'mouse-face 'highlight
                                   'rear-nonsticky t
                                   'keymap org-mouse-map
                                   ))
-       t)))
+         (throw 'exit t))))))
 
 (defun org-activate-angle-links (limit)
   "Run through the buffer and add overlays to links."
@@ -3881,11 +4238,6 @@
                                   'keymap org-mouse-map))
        t)))
 
-(defun org-font-lock-level ()
-  (save-excursion
-    (org-back-to-heading t)
-    (- (match-end 0) (match-beginning 0))))
-
 (defun org-outline-level ()
   (save-excursion
     (looking-at outline-regexp)
@@ -3906,20 +4258,20 @@
           '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
             (1 'org-table))
           ;; Links
+          (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
           (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
           (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
           (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
           (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
           (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
-          (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
+          '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
           '(org-hide-wide-columns (0 nil append))
           ;; TODO lines
           (list (concat "^\\*+[ \t]*" org-not-done-regexp)
                 '(1 'org-todo t))
           ;; Priorities
-          (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
+          (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
           ;; Special keywords
-          (list org-repeat-re  '(0 'org-special-keyword t))
           (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
           (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword 
t))
           (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
@@ -3942,9 +4294,13 @@
           '("^#.*" (0 'font-lock-comment-face t))
           ;; DONE
           (if org-fontify-done-headline
-              (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
+              (list (concat "^[*]+ +\\<\\("
+                            (mapconcat 'regexp-quote org-done-keywords "\\|")
+                            "\\)\\(.*\\)")
                     '(1 'org-done t) '(2 'org-headline-done t))
-            (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
+            (list (concat "^[*]+ +\\<\\("
+                          (mapconcat 'regexp-quote org-done-keywords "\\|")
+                          "\\)\\>")
                   '(1 'org-done t)))
           ;; Table stuff
           '("^[ \t]*\\(:.*\\)" (1 'org-table t))
@@ -4088,7 +4444,8 @@
                              (- (funcall outline-level) arg)))
        (org-show-subtree)))
 
-     ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
+     ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
+          (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
       ;; At a heading: rotate between three different views
       (org-back-to-heading)
       (let ((goal-column 0) eoh eol eos)
@@ -4102,20 +4459,30 @@
              (beginning-of-line 2)) (setq eol (point)))
          (outline-end-of-heading)   (setq eoh (point))
          (org-end-of-subtree t)
+         (unless (eobp)
          (skip-chars-forward " \t\n")
          (beginning-of-line 1) ; in case this is an item
+           )
          (setq eos (1- (point))))
        ;; Find out what to do next and set `this-command'
        (cond
         ((= eos eoh)
          ;; Nothing is hidden behind this heading
          (message "EMPTY ENTRY")
-         (setq org-cycle-subtree-status nil))
+         (setq org-cycle-subtree-status nil)
+         (save-excursion
+           (goto-char eos)
+           (outline-next-heading)
+           (if (org-invisible-p) (org-flag-heading nil))))
         ((>= eol eos)
          ;; Entire subtree is hidden in one line: open it
          (org-show-entry)
          (show-children)
          (message "CHILDREN")
+         (save-excursion
+           (goto-char eos)
+           (outline-next-heading)
+           (if (org-invisible-p) (org-flag-heading nil)))
          (setq org-cycle-subtree-status 'children)
          (run-hook-with-args 'org-cycle-hook 'children))
         ((and (eq last-command this-command)
@@ -4137,6 +4504,11 @@
 
      ((org-try-cdlatex-tab))
 
+     ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
+          (or (not (bolp))
+              (not (looking-at outline-regexp))))
+      (call-interactively (global-key-binding "\t")))
+
      ((if (and (memq org-cycle-emulate-tab '(white whitestart))
               (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
               (or (and (eq org-cycle-emulate-tab 'white)
@@ -4151,7 +4523,7 @@
          (progn
            (beginning-of-line 1)
            (and (looking-at "[ \t]+") (replace-match ""))))
-      (indent-relative))
+      (call-interactively (global-key-binding "\t")))
 
      (t (save-excursion
          (org-back-to-heading)
@@ -4177,13 +4549,13 @@
 first headline is not level one, then (hide-sublevels 1) gives confusing
 results."
   (interactive)
-  (hide-sublevels (save-excursion
+  (let ((level (save-excursion
                    (goto-char (point-min))
                    (if (re-search-forward (concat "^" outline-regexp) nil t)
                        (progn
                          (goto-char (match-beginning 0))
-                         (funcall outline-level))
-                     1))))
+                      (funcall outline-level))))))
+    (and level (hide-sublevels level))))
 
 (defun org-content (&optional arg)
   "Show all headlines in the buffer, like a table of contents.
@@ -4210,13 +4582,53 @@
 This function is the default value of the hook `org-cycle-hook'."
   (when (get-buffer-window (current-buffer))
     (cond
-     ((eq state 'overview) (org-first-headline-recenter 1))
+;     ((eq state 'overview) (org-first-headline-recenter 1))
+;     ((eq state 'overview) (org-beginning-of-line))
      ((eq state 'content)  nil)
      ((eq state 'all)      nil)
      ((eq state 'folded)   nil)
      ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
      ((eq state 'subtree)  (or (org-subtree-end-visible-p) (recenter 1))))))
 
+
+(defun org-cycle-show-empty-lines (state)
+  "Show empty lines above all visible headlines.
+The region to be covered depends on STATE when called through
+`org-cycle-hook'.  Lisp program can use t for STATE to get the
+entire buffer covered.  Note that an empty line is only shown if there
+are at least `org-cycle-separator-lines' empty lines before the headeline."
+  (when (> org-cycle-separator-lines 0)
+    (save-excursion
+      (let* ((n org-cycle-separator-lines)
+            (re (cond
+                 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
+                 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
+                 (t (let ((ns (number-to-string (- n 2))))
+                      (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
+                              "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
+            beg end)
+       (cond
+        ((memq state '(overview contents t))
+         (setq beg (point-min) end (point-max)))
+        ((memq state '(children folded))
+         (setq beg (point) end (progn (org-end-of-subtree t t)
+                                      (beginning-of-line 2)
+                                      (point)))))
+       (when beg
+         (goto-char beg)
+         (while (re-search-forward re end t)
+           (if (not (get-char-property (match-end 1) 'invisible))
+               (outline-flag-region
+                (match-beginning 1) (match-end 1) nil)))))))
+  ;; Never hide empty lines at the end of the file.
+  (save-excursion
+    (goto-char (point-max))
+    (outline-previous-heading)
+    (outline-end-of-heading)
+    (if (and (looking-at "[ \t\n]+")
+            (= (match-end 0) (point-max)))
+       (outline-flag-region (point) (match-end 0) nil))))
+
 (defun org-subtree-end-visible-p ()
   "Is the end of the current subtree visible?"
   (pos-visible-in-window-p
@@ -4238,27 +4650,27 @@
 (let ((cmds '(isearch-forward isearch-backward)) cmd)
   (while (setq cmd (pop cmds))
     (substitute-key-definition cmd cmd org-goto-map global-map)))
-(define-key org-goto-map "\C-m"     'org-goto-ret)
-(define-key org-goto-map [(left)]   'org-goto-left)
-(define-key org-goto-map [(right)]  'org-goto-right)
-(define-key org-goto-map [(?q)]     'org-goto-quit)
-(define-key org-goto-map [(control ?g)] 'org-goto-quit)
-(define-key org-goto-map "\C-i" 'org-cycle)
-(define-key org-goto-map [(tab)] 'org-cycle)
-(define-key org-goto-map [(down)] 'outline-next-visible-heading)
-(define-key org-goto-map [(up)] 'outline-previous-visible-heading)
-(define-key org-goto-map "n" 'outline-next-visible-heading)
-(define-key org-goto-map "p" 'outline-previous-visible-heading)
-(define-key org-goto-map "f" 'outline-forward-same-level)
-(define-key org-goto-map "b" 'outline-backward-same-level)
-(define-key org-goto-map "u" 'outline-up-heading)
-(define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
-(define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
-(define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
-(define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
-(define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
+(org-defkey org-goto-map "\C-m"     'org-goto-ret)
+(org-defkey org-goto-map [(left)]   'org-goto-left)
+(org-defkey org-goto-map [(right)]  'org-goto-right)
+(org-defkey org-goto-map [(?q)]     'org-goto-quit)
+(org-defkey org-goto-map [(control ?g)] 'org-goto-quit)
+(org-defkey org-goto-map "\C-i" 'org-cycle)
+(org-defkey org-goto-map [(tab)] 'org-cycle)
+(org-defkey org-goto-map [(down)] 'outline-next-visible-heading)
+(org-defkey org-goto-map [(up)] 'outline-previous-visible-heading)
+(org-defkey org-goto-map "n" 'outline-next-visible-heading)
+(org-defkey org-goto-map "p" 'outline-previous-visible-heading)
+(org-defkey org-goto-map "f" 'outline-forward-same-level)
+(org-defkey org-goto-map "b" 'outline-backward-same-level)
+(org-defkey org-goto-map "u" 'outline-up-heading)
+(org-defkey org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
+(org-defkey org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
+(org-defkey org-goto-map "\C-c\C-f" 'outline-forward-same-level)
+(org-defkey org-goto-map "\C-c\C-b" 'outline-backward-same-level)
+(org-defkey org-goto-map "\C-c\C-u" 'outline-up-heading)
 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
-  (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
+  (while l (org-defkey org-goto-map (int-to-string (pop l)) 'digit-argument)))
 
 (defconst org-goto-help
 "Select a location to jump to, press RET
@@ -4474,10 +4886,13 @@
             pos)
        (cond
         ((and (org-on-heading-p) (bolp)
-              (save-excursion (backward-char 1) (not (org-invisible-p))))
+              (or (bobp)
+                  (save-excursion (backward-char 1) (not (org-invisible-p)))))
          (open-line (if blank 2 1)))
-        ((and (bolp) (save-excursion
-                       (backward-char 1) (not (org-invisible-p))))
+        ((and (bolp)
+              (or (bobp)
+                  (save-excursion
+                    (backward-char 1) (not (org-invisible-p)))))
          nil)
         (t (newline (if blank 2 1))))
        (insert head) (just-one-space)
@@ -4500,8 +4915,8 @@
       (looking-at org-todo-line-regexp))
     (if (or arg
            (not (match-beginning 2))
-           (equal (match-string 2) org-done-string))
-       (insert (car org-todo-keywords) " ")
+           (member (match-string 2) org-done-keywords))
+       (insert (car org-todo-keywords-1) " ")
       (insert (match-string 2) " "))))
 
 ;;; Promotion and Demotion
@@ -4724,6 +5139,7 @@
     (setq txt (buffer-substring beg end))
     (delete-region beg end)
     (insert txt)
+    (or (bolp) (insert "\n"))
     (goto-char ins-point)
     (if folded (hide-subtree))
     (move-marker ins-point nil)))
@@ -4749,7 +5165,9 @@
 If CUT is non-nil, actually cut the subtree."
   (interactive)
   (let (beg end folded)
-    (org-back-to-heading)
+    (if (interactive-p)
+       (org-back-to-heading nil) ; take what looks like a subtree
+      (org-back-to-heading t)) ; take what is really there
     (setq beg (point))
     (save-match-data
       (save-excursion (outline-end-of-heading)
@@ -4888,7 +5306,7 @@
   (save-excursion
     (narrow-to-region
      (progn (org-back-to-heading) (point))
-     (progn (org-end-of-subtree t) (point)))))
+     (progn (org-end-of-subtree t t) (point)))))
 
 
 ;;; Outline Sorting
@@ -5130,7 +5548,7 @@
 the whole buffer."
   (interactive "P")
   (save-excursion
-    (let* ((buffer-invisibility-spec nil) ; Emacs 21 compatibility
+    (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
           (beg (progn (outline-back-to-heading) (point)))
           (end (move-marker (make-marker)
                             (progn (outline-next-heading) (point))))
@@ -5214,13 +5632,24 @@
        (concat (make-string i1 ?\ ) l)
       l)))
 
+(defcustom org-empty-line-terminates-plain-lists nil
+  "Non-nil means, an empty line ends all plain list levels.
+When nil, empty lines are part of the preceeding item."
+  :group 'org-plain-lists
+  :type 'boolean)
+
 (defun org-beginning-of-item ()
   "Go to the beginning of the current hand-formatted item.
 If the cursor is not in an item, throw an error."
   (interactive)
   (let ((pos (point))
-       (limit (save-excursion (org-back-to-heading)
-                              (beginning-of-line 2) (point)))
+       (limit (save-excursion
+                (condition-case nil
+                    (progn
+                      (org-back-to-heading)
+                      (beginning-of-line 2) (point))
+                  (error (point-min)))))
+       (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
        ind ind1)
     (if (org-at-item-p)
        (beginning-of-line 1)
@@ -5230,12 +5659,14 @@
       (if (catch 'exit
            (while t
              (beginning-of-line 0)
-             (if (< (point) limit) (throw 'exit nil))
-             (unless (looking-at "[ \t]*$")
+             (if (or (bobp) (< (point) limit)) (throw 'exit nil))
+
+             (if (looking-at "[ \t]*$")
+                 (setq ind1 ind-empty)
                (skip-chars-forward " \t")
-               (setq ind1 (current-column))
+               (setq ind1 (current-column)))
                (if (< ind1 ind)
-                   (throw 'exit (org-at-item-p))))))
+                 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
          nil
        (goto-char pos)
        (error "Not in an item")))))
@@ -5244,22 +5675,27 @@
   "Go to the end of the current hand-formatted item.
 If the cursor is not in an item, throw an error."
   (interactive)
-  (let ((pos (point))
+  (let* ((pos (point))
+        ind1
+        (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
        (limit (save-excursion (outline-next-heading) (point)))
        (ind (save-excursion
               (org-beginning-of-item)
               (skip-chars-forward " \t")
               (current-column)))
-       ind1)
-    (if (catch 'exit
+        (end (catch 'exit
          (while t
            (beginning-of-line 2)
-           (if (>= (point) limit) (throw 'exit t))
-           (unless (looking-at "[ \t]*$")
+                 (if (eobp) (throw 'exit (point)))
+                 (if (>= (point) limit) (throw 'exit (point-at-bol)))
+                 (if (looking-at "[ \t]*$")
+                     (setq ind1 ind-empty)
              (skip-chars-forward " \t")
-             (setq ind1 (current-column))
-             (if (<= ind1 ind) (throw 'exit t)))))
-       (beginning-of-line 1)
+                   (setq ind1 (current-column)))
+                 (if (<= ind1 ind)
+                     (throw 'exit (point-at-bol)))))))
+    (if end
+       (goto-char end)
       (goto-char pos)
       (error "Not in an item"))))
 
@@ -5338,7 +5774,11 @@
       (while t
        (beginning-of-line 0)
        (if (looking-at "[ \t]*$")
-           nil
+           (if org-empty-line-terminates-plain-lists
+               (progn
+                 (goto-char pos)
+                 (error "Cannot move this item further up"))
+             nil)
          (if (<= (setq ind1 (org-get-indentation)) ind)
              (throw 'exit t)))))
     (condition-case nil
@@ -5468,16 +5908,16 @@
 open TODO items and archive them (after getting confirmation from the user).
 If the cursor is not at a headline when this comand is called, try all level
 1 trees.  If the cursor is on a headline, only try the direct children of
-this heading. "
+this heading."
   (interactive "P")
   (if find-done
       (org-archive-all-done)
     ;; Save all relevant TODO keyword-relatex variables
 
     (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite 
compiler
-         (tr-org-todo-keywords org-todo-keywords)
-         (tr-org-todo-interpretation org-todo-interpretation)
-         (tr-org-done-string org-done-string)
+         (tr-org-todo-keywords-1 org-todo-keywords-1)
+         (tr-org-todo-kwd-alist org-todo-kwd-alist)
+         (tr-org-done-keywords org-done-keywords)
          (tr-org-todo-regexp org-todo-regexp)
          (tr-org-todo-line-regexp org-todo-line-regexp)
          (tr-org-odd-levels-only org-odd-levels-only)
@@ -5488,8 +5928,10 @@
 
       ;; Try to find a local archive location
       (save-excursion
+       (save-restriction
+         (widen)
        (if (or (re-search-backward re nil t) (re-search-forward re nil t))
-           (setq org-archive-location (match-string 1))))
+             (setq org-archive-location (match-string 1)))))
 
       (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
          (progn
@@ -5516,7 +5958,8 @@
        ;; Enforce org-mode for the archive buffer
        (if (not (org-mode-p))
            ;; Force the mode for future visits.
-           (let ((org-insert-mode-line-in-empty-file t))
+           (let ((org-insert-mode-line-in-empty-file t)
+                 (org-inhibit-startup t))
              (call-interactively 'org-mode)))
        (when newfile-p
          (goto-char (point-max))
@@ -5524,13 +5967,13 @@
                          (buffer-file-name this-buffer))))
        ;; Force the TODO keywords of the original buffer
        (let ((org-todo-line-regexp tr-org-todo-line-regexp)
-             (org-todo-keywords tr-org-todo-keywords)
-             (org-todo-interpretation tr-org-todo-interpretation)
-             (org-done-string tr-org-done-string)
+             (org-todo-keywords-1 tr-org-todo-keywords-1)
+             (org-todo-kwd-alist tr-org-todo-kwd-alist)
+             (org-done-keywords tr-org-done-keywords)
              (org-todo-regexp tr-org-todo-regexp)
              (org-todo-line-regexp tr-org-todo-line-regexp)
              (org-odd-levels-only
-              (if (local-variable-p 'org-odd-levels-only)
+              (if (local-variable-p 'org-odd-levels-only (current-buffer))
                   org-odd-levels-only
                 tr-org-odd-levels-only)))
          (goto-char (point-min))
@@ -5556,10 +5999,10 @@
            (goto-char (point-max)) (insert "\n"))
          ;; Paste
          (org-paste-subtree (org-get-legal-level level 1))
-         ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
+         ;; Mark the entry as done, i.e. set to last word in 
org-todo-keywords-1 FIXME: not right anymore!!!!!!!
          (if org-archive-mark-done
              (let (org-log-done)
-               (org-todo (length org-todo-keywords))))
+               (org-todo (length org-todo-keywords-1))))
          ;; Move cursor to right after the TODO keyword
          (when org-archive-stamp-time
            (beginning-of-line 1)
@@ -5653,7 +6096,7 @@
 (defun org-toggle-tag (tag &optional onoff)
   "Toggle the tag TAG for the current line.
 If ONOFF is `on' or `off', don't toggle but set to this state."
-  (unless (org-on-heading-p) (error "Not on headling"))
+  (unless (org-on-heading-p t) (error "Not on headling"))
   (let (res current)
     (save-excursion
       (beginning-of-line)
@@ -5749,6 +6192,8 @@
   "Table row types, non-nil only for the duration of a comand.")
 (defvar org-table-current-begin-line nil
   "Table begin line, non-nil only for the duration of a comand.")
+(defvar org-table-current-begin-pos nil
+  "Table begin position, non-nil only for the duration of a comand.")
 (defvar org-table-dlines nil
   "Vector of data line line numbers in the current table.")
 (defvar org-table-hlines nil
@@ -5760,11 +6205,17 @@
   "Regular expression for matching ranges in formulas.")
 
 (defconst org-table-range-regexp2
-   
"@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[a-zA-Z0-9]+\\)?\\(address@hidden([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[a-zA-Z0-9]+\\)?\\)?\\|\\$[a-zA-Z0-9]+\\.\\.\\$[a-zA-Z0-9]+"
-  "Regular expression to recognize ranges in formulas for highlighting.")
-
-(defvar org-inhibit-highlight-removal nil)
+  (concat
+   "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" 
"\\$[a-zA-Z0-9]+" "\\)"
+   "\\.\\."
+   "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" 
"\\$[a-zA-Z0-9]+" "\\)")
+  "Match a range for reference display.")
+
+(defconst org-table-translate-regexp
+  (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
+  "Match a reference that needs translation, for reference display.")
 
+(defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
 
 (defun org-table-create-with-table.el ()
   "Use the table.el package to insert a new table.
@@ -5783,8 +6234,9 @@
 
 (defun org-table-create-or-convert-from-region (arg)
   "Convert region to table, or create an empty table.
-If there is an active region, convert it to a table.  If there is no such
-region, create an empty table."
+If there is an active region, convert it to a table, using the function
+`org-table-convert-region'.
+If there is no such region, create an empty table with `org-table-create'."
   (interactive "P")
   (if (org-region-active-p)
       (org-table-convert-region (region-beginning) (region-end) arg)
@@ -5827,7 +6279,9 @@
 The region goes from BEG0 to END0, but these borders will be moved
 slightly, to make sure a beginning of line in the first line is included.
 When NSPACE is non-nil, it indicates the minimum number of spaces that
-separate columns (default: just one space)."
+separate columns.  By default, the function first checks if every line
+contains at lease one TAB.  If yes, it assumes that the material is TAB
+separated.  If not, it assumes a single space as separator."
   (interactive "rP")
   (let* ((beg (min beg0 end0))
         (end (max beg0 end0))
@@ -6249,9 +6703,13 @@
 the cursor is moved with it.  Therefore, repeating this command causes the
 column to be filled row-by-row.
 If the variable `org-table-copy-increment' is non-nil and the field is an
-integer, it will be incremented while copying."
+integer or a timestamp, it will be incremented while copying.  In the case of
+a timestamp, if the cursor is on the year, change the year.  If it is on the
+month or the day, change that.  Point will stay on the current date field
+in order to easily repeat the interval."
   (interactive "p")
   (let* ((colpos (org-table-current-column))
+        (col (current-column))
         (field (org-table-get-field))
         (non-empty (string-match "[^ \t]" field))
         (beg (org-table-begin))
@@ -6279,8 +6737,12 @@
                   (string-match "^[0-9]+$" txt))
              (setq txt (format "%d" (+ (string-to-number txt) 1))))
          (insert txt)
-         (org-table-maybe-recalculate-line)
-         (org-table-align))
+         (move-to-column col)
+         (if (and org-table-copy-increment (org-at-timestamp-p t))
+             (org-timestamp-up 1)
+           (org-table-maybe-recalculate-line))
+         (org-table-align)
+         (move-to-column col))
       (error "No non-empty field found"))))
 
 (defun org-table-check-inside-data-field ()
@@ -6344,21 +6806,26 @@
           (eql (org-table-get-stored-formulas))
           (dline (org-table-current-dline))
           (ref (format "@%d$%d" dline col))
+          (ref1 (org-table-convert-refs-to-an ref))
           (fequation (or (assoc name eql) (assoc ref eql)))
-          (cequation (assoc (int-to-string col) eql)))
+          (cequation (assoc (int-to-string col) eql))
+          (eqn (or fequation cequation)))
       (goto-char pos)
       (condition-case nil
-         (org-show-reference 'local)
+         (org-table-show-reference 'local)
        (error nil))
-      (message "line @%d, col $%s%s, ref @%d$%d%s%s"
+      (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
               dline col
               (if cname (concat " or $" cname) "")
-              dline col
+              dline col ref1
               (if name (concat " or $" name) "")
               ;; FIXME: formula info not correct if special table line
-              (if (or fequation cequation)
-                  (concat ", " (if fequation "field" "column")
-                          " formula applies" "")
+              (if eqn
+                  (concat ", formula: "
+                          (org-table-formula-to-user
+                           (concat
+                            (if (string-match "address@hidden"(car eqn)) "" 
"$")
+                            (car eqn) "=" (cdr eqn))))
                 "")))))
 
 (defun org-table-current-column ()
@@ -6635,9 +7102,9 @@
         (org-table-align))
     (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
 
-(defun org-table-insert-hline (&optional arg)
+(defun org-table-insert-hline (&optional above)
   "Insert a horizontal-line below the current line into the table.
-With prefix ARG, insert above the current line."
+With prefix ABOVE, insert above the current line."
   (interactive "P")
   (if (not (org-at-table-p))
       (error "Not at a table"))
@@ -6649,12 +7116,25 @@
                  (concat "+" (make-string (- (match-end 1) (match-beginning 1))
                                           ?-) "|") t t line)))
     (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
-    (beginning-of-line (if arg 1 2))
+    (beginning-of-line (if above 1 2))
     (insert line "\n")
-    (beginning-of-line (if arg 1 -1))
+    (beginning-of-line (if above 1 -1))
     (move-to-column col)
     (and org-table-overlay-coordinates (org-table-align))))
 
+(defun org-table-hline-and-move (&optional same-column)
+  "Insert a hline and move to the row below that line."
+  (interactive "P")
+  (let ((col (org-table-current-column)))
+    (org-table-maybe-eval-formula)
+    (org-table-maybe-recalculate-line)
+    (org-table-insert-hline)
+    (end-of-line 2)
+    (if (looking-at "\n[ \t]*|-")
+       (progn (insert "\n|") (org-table-align))
+      (org-table-next-field))
+    (if same-column (org-table-goto-column col))))
+
 (defun org-table-clean-line (s)
   "Convert a table line S into a string with only \"|\" and space.
 In particular, this does handle wide and invisible characters."
@@ -6959,15 +7439,14 @@
       (switch-to-buffer-other-window "*Org tmp*")
       (erase-buffer)
       (insert "#\n# Edit field and finish with C-c C-c\n#\n")
-      (org-mode)
+      (let ((org-inhibit-startup t)) (org-mode))
       (goto-char (setq p (point-max)))
       (insert (org-trim field))
       (remove-text-properties p (point-max)
                              '(invisible t org-cwidth t display t
                                          intangible t))
       (goto-char p)
-      (org-set-local 'org-finish-function
-                    'org-table-finish-edit-field)
+      (org-set-local 'org-finish-function 'org-table-finish-edit-field)
       (org-set-local 'org-window-configuration cw)
       (org-set-local 'org-field-marker pos)
       (message "Edit and finish with C-c C-c"))))
@@ -6997,8 +7476,8 @@
 
 (defun org-trim (s)
   "Remove whitespace at beginning and end of string."
-  (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
-  (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
+  (if (string-match "^[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
+  (if (string-match "[ \t\n\r]+$" s) (setq s (replace-match "" t t s)))
   s)
 
 (defun org-wrap (string &optional width lines)
@@ -7159,21 +7638,25 @@
      ((equal n 0)                             nil)
      (t n))))
 
-(defun org-table-current-field-formula ()
+(defun org-table-current-field-formula (&optional key noerror)
   "Return the formula active for the current field.
-Assumes that specials are in place."
+Assumes that specials are in place.
+If KEY is given, return the key to this formula.
+Otherwise return the formula preceeded with \"=\" or \":=\"."
   (let* ((name (car (rassoc (list (org-current-line)
                                  (org-table-current-column))
                            org-table-named-field-locations)))
         (col (org-table-current-column))
         (scol (int-to-string col))
         (ref (format "@%d$%d" (org-table-current-dline) col))
-        (stored-list (org-table-get-stored-formulas))
+        (stored-list (org-table-get-stored-formulas noerror))
         (ass (or (assoc name stored-list)
                  (assoc ref stored-list)
                  (assoc scol stored-list))))
+    (if key
+       (car ass)
     (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
-                   (cdr ass)))))
+                     (cdr ass))))))
 
 (defun org-table-get-formula (&optional equation named)
   "Read a formula from the minibuffer, offer stored formula as default.
@@ -7199,11 +7682,16 @@
               stored)
              ((stringp equation)
               equation)
-             (t (read-string
-                 (format "%s formula $%s=" (if named "Field" "Column") scol)
-                 (or stored "") 'org-table-formula-history
-                 ;stored
-                 ))))
+             (t (org-table-formula-from-user
+                 (read-string
+                  (org-table-formula-to-user
+                   (format "%s formula %s%s="
+                           (if named "Field" "Column")
+                           (if (member (string-to-char scol) '(?$ ?@)) "" "$")
+                           scol))
+                  (if stored (org-table-formula-to-user stored) "")
+                  'org-table-formula-history
+                  )))))
         mustsave)
     (when (not (string-match "\\S-" eq))
       ;; remove formula
@@ -7225,7 +7713,7 @@
 
 (defun org-table-store-formulas (alist)
   "Store the list of formulas below the current table."
-  (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
+  (setq alist (sort alist 'org-table-formula-less-p))
   (save-excursion
     (goto-char (org-table-end))
     (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
@@ -7242,7 +7730,20 @@
                       alist "::")
            "\n")))
 
-(defun org-table-get-stored-formulas ()
+(defsubst org-table-formula-make-cmp-string (a)
+  (when (string-match 
"^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
+    (concat
+     (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) 
"")
+     (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) 
"")
+     (if (match-end 5) (concat "@@" (match-string 5 a))))))
+
+(defun org-table-formula-less-p (a b)
+  "Compare two formulas for sorting."
+  (let ((as (org-table-formula-make-cmp-string (car a)))
+       (bs (org-table-formula-make-cmp-string (car b))))
+    (and as bs (string< as bs))))
+
+(defun org-table-get-stored-formulas (&optional noerror)
   "Return an alist with the stored formulas directly after current table."
   (interactive)
   (let (scol eq eq-alist strings string seen)
@@ -7258,7 +7759,12 @@
                  eq (match-string 3 string)
                  eq-alist (cons (cons scol eq) eq-alist))
            (if (member scol seen)
-               (error "Double definition `$%s=' in TBLFM line, please fix by 
hand" scol)
+                (if noerror
+                    (progn
+                      (message "Double definition `$%s=' in TBLFM line, please 
fix by hand" scol)
+                      (ding)
+                      (sit-for 2))
+                  (error "Double definition `$%s=' in TBLFM line, please fix 
by hand" scol))
              (push scol seen))))))
     (nreverse eq-alist)))
 
@@ -7297,6 +7803,7 @@
            org-table-local-parameters nil
            org-table-named-field-locations nil
            org-table-current-begin-line nil
+           org-table-current-begin-pos nil
            org-table-current-line-types nil)       
       (goto-char beg)
       (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
@@ -7334,6 +7841,7 @@
       ;; Analyse the line types
       (goto-char beg)
       (setq org-table-current-begin-line (org-current-line)
+           org-table-current-begin-pos (point)
            l org-table-current-begin-line)      
       (while (looking-at "[ \t]*|\\(-\\)?")
        (push (if (match-end 1) 'hline 'dline) types)
@@ -7344,13 +7852,6 @@
            org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
            org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
 
-(defun org-this-word ()
-  ;; Get the current word
-  (save-excursion
-    (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
-         (end (progn (skip-chars-forward "^ \t\n") (point))))
-      (buffer-substring-no-properties beg end))))
-
 (defun org-table-maybe-eval-formula ()
   "Check if the current field starts with \"=\" or \":=\".
 If yes, store the formula and apply it."
@@ -7364,7 +7865,8 @@
              eq (match-string 1 field))
        (if (or (fboundp 'calc-eval)
                (equal (substring eq 0 (min 2 (length eq))) "'("))
-           (org-table-eval-formula (if named '(4) nil) eq)
+           (org-table-eval-formula (if named '(4) nil)
+                                   (org-table-formula-from-user eq))
          (error "Calc does not seem to be installed, and is needed to evaluate 
the formula"))))))
 
 (defvar org-recalc-commands nil
@@ -7485,7 +7987,7 @@
 
 When called with two `C-u' prefixes, insert the active equation
 for the field back into the current field, so that it can be
-edited there.  This is useful in order to use \\[org-show-reference]
+edited there.  This is useful in order to use \\[org-table-show-reference]
 to check the referenced fields.
 
 When called, the command first prompts for a formula, which is read in
@@ -7596,17 +8098,16 @@
                 t t form)))
        (setq form0 form)
        ;; Insert the references to fields in same row
-       (while (string-match "\\$\\([0-9]+\\)?" form)
-         (setq n (if (match-beginning 1)
-                     (string-to-number (match-string 1 form))
-                   n0)
-               x (nth (1- n) fields))
+       (while (string-match "\\$\\([0-9]+\\)" form)
+         (setq n (string-to-number (match-string 1 form))
+               x (nth (1- (if (= n 0) n0 n)) fields))
          (unless x (error "Invalid field specifier \"%s\""
                           (match-string 0 form)))
          (setq form (replace-match
                      (save-match-data
                        (org-table-make-reference x nil numbers lispp))
                      t t form)))
+
        (if lispp
            (setq ev (condition-case nil
                         (eval (eval (read form)))
@@ -7738,7 +8239,7 @@
            (setq i 0 hdir "+")
            (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
       (if (and (not hn) on (not odir))
-         (error "should never happen");;(aref org-table-dlines on) FIXME
+         (error "should never happen");;(aref org-table-dlines on)
        (if (and hn (> hn 0))
            (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
        (if on
@@ -7837,7 +8338,7 @@
       (goto-char beg)
       (and all (message "Re-applying formulas to full table..."))
       (while (re-search-forward line-re end t)
-       (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
+       (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
          ;; Unprotected line, recalculate
          (and all (message "Re-applying formulas to full table...(line %d)"
                            (setq cnt (1+ cnt))))
@@ -7924,32 +8425,74 @@
       (and (fboundp 'constants-get) (constants-get const))
       "#UNDEFINED_NAME"))
 
-(defvar org-edit-formulas-map (make-sparse-keymap))
-(define-key org-edit-formulas-map "\C-c\C-c"      'org-finish-edit-formulas)
-(define-key org-edit-formulas-map "\C-c\C-q"      'org-abort-edit-formulas)
-(define-key org-edit-formulas-map "\C-c?"         'org-show-reference)
-(define-key org-edit-formulas-map [(shift up)]    'org-table-edit-line-up)
-(define-key org-edit-formulas-map [(shift down)]  'org-table-edit-line-down)
-(define-key org-edit-formulas-map [(shift left)] 
'org-table-edit-backward-field)
-(define-key org-edit-formulas-map [(shift right)] 'org-table-edit-next-field)
-(define-key org-edit-formulas-map [(meta up)]     'org-table-edit-scroll-down)
-(define-key org-edit-formulas-map [(meta down)]   'org-table-edit-scroll)
-(define-key org-edit-formulas-map [(meta tab)]    'lisp-complete-symbol)
-(define-key org-edit-formulas-map "\M-\C-i"       'lisp-complete-symbol)
-(define-key org-edit-formulas-map [(tab)]         
'org-edit-formula-lisp-indent)
-(define-key org-edit-formulas-map "\C-i"          
'org-edit-formula-lisp-indent)
+(defvar org-table-fedit-map (make-sparse-keymap))
+(org-defkey org-table-fedit-map "\C-x\C-s"      'org-table-fedit-finish)
+(org-defkey org-table-fedit-map "\C-c\C-s"      'org-table-fedit-finish)
+(org-defkey org-table-fedit-map "\C-c\C-c"      'org-table-fedit-finish)
+(org-defkey org-table-fedit-map "\C-c\C-q"      'org-table-fedit-abort)
+(org-defkey org-table-fedit-map "\C-c?"         'org-table-show-reference)
+(org-defkey org-table-fedit-map [(meta shift up)]    'org-table-fedit-line-up)
+(org-defkey org-table-fedit-map [(meta shift down)]  
'org-table-fedit-line-down)
+(org-defkey org-table-fedit-map [(shift up)]    'org-table-fedit-ref-up)
+(org-defkey org-table-fedit-map [(shift down)]  'org-table-fedit-ref-down)
+(org-defkey org-table-fedit-map [(shift left)]  'org-table-fedit-ref-left)
+(org-defkey org-table-fedit-map [(shift right)] 'org-table-fedit-ref-right)
+(org-defkey org-table-fedit-map [(meta up)]     'org-table-fedit-scroll-down)
+(org-defkey org-table-fedit-map [(meta down)]   'org-table-fedit-scroll)
+(org-defkey org-table-fedit-map [(meta tab)]    'lisp-complete-symbol)
+(org-defkey org-table-fedit-map "\M-\C-i"       'lisp-complete-symbol)
+(org-defkey org-table-fedit-map [(tab)]         'org-table-fedit-lisp-indent)
+(org-defkey org-table-fedit-map "\C-i"          'org-table-fedit-lisp-indent)
+(org-defkey org-table-fedit-map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
+(org-defkey org-table-fedit-map "\C-c}"    'org-table-fedit-toggle-coordinates)
+
+(easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas 
Menu"
+  '("Edit-Formulas"
+    ["Finish and Install" org-table-fedit-finish t]
+    ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c 
C-c"]
+    ["Abort" org-table-fedit-abort t]
+    "--"
+    ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
+    ["Complete Lisp Symbol" lisp-complete-symbol t]
+    "--"
+    "Shift Reference at Point"
+    ["Up" org-table-fedit-ref-up t]
+    ["Down" org-table-fedit-ref-down t]
+    ["Left" org-table-fedit-ref-left t]
+    ["Right" org-table-fedit-ref-right t]
+    "-"
+    "Change Test Row for Column Formulas"
+    ["Up" org-table-fedit-line-up t]
+    ["Down" org-table-fedit-line-down t]
+    "--"
+    ["Scroll Table Window" org-table-fedit-scroll t]
+    ["Scroll Table Window down" org-table-fedit-scroll-down t]
+    ["Show Table Grid" org-table-fedit-toggle-coordinates
+     :style toggle :selected (with-current-buffer (marker-buffer org-pos)
+                              org-table-overlay-coordinates)]
+    "--"
+    ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
+     :style toggle :selected org-table-buffer-is-an]))
 
 (defvar org-pos)
 
 (defun org-table-edit-formulas ()
   "Edit the formulas of the current table in a separate buffer."
   (interactive)
+  (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
+    (beginning-of-line 0))
   (unless (org-at-table-p) (error "Not at a table"))
   (org-table-get-specials)
-  (let ((eql (org-table-get-stored-formulas))
+  (let ((key (org-table-current-field-formula 'key 'noerror))
+       (eql (sort (org-table-get-stored-formulas 'noerror)
+                   'org-table-formula-less-p))
        (pos (move-marker (make-marker) (point)))
+       (startline 1)
        (wc (current-window-configuration))
-       entry s)
+       (titles '((column . "# Column Formulas\n")
+                 (field . "# Field Formulas\n")
+                 (named . "# Named Field Formulas\n")))
+       entry s type title)
     (switch-to-buffer-other-window "*Edit Formulas*")
     (erase-buffer)
     ;; Keep global-font-lock-mode from turning on font-lock-mode
@@ -7958,61 +8501,253 @@
     (org-set-local 'font-lock-global-modes (list 'not major-mode))
     (org-set-local 'org-pos pos)
     (org-set-local 'org-window-configuration wc)
-    (use-local-map org-edit-formulas-map)
-    (org-add-hook 'post-command-hook 'org-table-edit-formulas-post-command t t)
-    (setq s "# `C-c C-c' to finish, `C-u C-c C-c' to also apply, `C-c C-q' to 
abort.
-# `TAB' to pretty-print Lisp expressions, `M-TAB' to complete List symbols
-# `M-up/down' to scroll table, `S-up/down' to change line for column 
formulas\n\n")
-
-    (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
-    (insert s)
+    (use-local-map org-table-fedit-map)
+    (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
+    (easy-menu-add org-table-fedit-menu)
+    (setq startline (org-current-line))
     (while (setq entry (pop eql))
+      (setq type (cond
+                 ((equal (string-to-char (car entry)) ?@) 'field)
+                 ((string-match "^[0-9]" (car entry)) 'column)
+                 (t 'named)))
+      (when (setq title (assq type titles))
+       (or (bobp) (insert "\n"))
+       (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
+       (setq titles (delq title titles)))
+      (if (equal key (car entry)) (setq startline (org-current-line)))
       (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
                      (car entry) " = " (cdr entry) "\n"))
       (remove-text-properties 0 (length s) '(face nil) s)
       (insert s))
-    (goto-char (point-min))
-    (message "Edit formulas and finish with `C-c C-c'.")))
+    (if (eq org-table-use-standard-references t)
+       (org-table-fedit-toggle-ref-type))
+    (goto-line startline)
+    (message "Edit formulas and finish with `C-c C-c'.  See menu for more 
commands.")))
 
-(defun org-table-edit-formulas-post-command ()
+(defun org-table-fedit-post-command ()
   (when (not (memq this-command '(lisp-complete-symbol)))
     (let ((win (selected-window)))
       (save-excursion
        (condition-case nil
-           (org-show-reference)
+           (org-table-show-reference)
          (error nil))
        (select-window win)))))
 
-(defun org-finish-edit-formulas (&optional arg)
-  "Parse the buffer for formula definitions and install them.
-With prefix ARG, apply the new formulas to the table."
-  (interactive "P")
-  (org-table-remove-rectangle-highlight)
-  (let ((pos org-pos) eql var form)
-    (setq org-pos nil)
-    (goto-char (point-min))
-    (while (re-search-forward
-           "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ 
\t]+.*$\\)*\\)"
-           nil t)
-      (setq var (if (match-end 2) (match-string 2) (match-string 1))
-           form (match-string 3))
-      (setq form (org-trim form))
-      (while (string-match "[ \t]*\n[ \t]*" form)
-       (setq form (replace-match " " t t form)))
-      (push (cons var form) eql))
-    (set-window-configuration org-window-configuration)
-    (select-window (get-buffer-window (marker-buffer pos)))
-    (goto-char pos)
-    (unless (org-at-table-p)
-      (error "Lost table position - cannot install formulae"))
-    (org-table-store-formulas eql)
-    (move-marker pos nil)
-    (kill-buffer "*Edit Formulas*")
-    (if arg
-       (org-table-recalculate 'all)
-      (message "New formulas installed - press C-u C-c C-c to apply."))))
+(defun org-table-formula-to-user (s)
+  "Convert a formula from internal to user representation."
+  (if (eq org-table-use-standard-references t)
+      (org-table-convert-refs-to-an s)
+    s))
+
+(defun org-table-formula-from-user (s)
+  "Convert a formula from user to internal representation."
+  (if org-table-use-standard-references
+      (org-table-convert-refs-to-rc s)
+    s))
+
+(defun org-table-convert-refs-to-rc (s)
+  "Convert spreadsheet references from AB7 to @7$28.
+Works for single references, but also for entire formulas and even the
+full TBLFM line."
+  (let ((start 0))
+    (while (string-match 
"\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
+      (cond
+       ((match-end 3)
+       ;; format match, just advance
+       (setq start (match-end 0)))
+       ((and (> (match-beginning 0) 0)
+            (equal ?. (aref s (max (1- (match-beginning 0)) 0))))
+       ;; 3.e5 or something like this.  FIXME: is this ok????
+       (setq start (match-end 0)))
+       (t
+       (setq start (match-beginning 0)
+             s (replace-match
+                (if (equal (match-string 2 s) "&")
+                    (format "$%d" (org-letters-to-number (match-string 1 s)))
+                  (format "@%d$%d"
+                          (string-to-number (match-string 2 s))
+                          (org-letters-to-number (match-string 1 s))))
+                t t s)))))
+    s))
+
+(defun org-table-convert-refs-to-an (s)
+  "Convert spreadsheet references from to @7$28 to AB7.
+Works for single references, but also for entire formulas and even the
+full TBLFM line."
+  (while (string-match "@\\([0-9]+\\)$\\([0-9]+\\)" s)
+    (setq s (replace-match
+            (format "%s%d"
+                    (org-number-to-letters
+                     (string-to-number (match-string 2 s)))
+                    (string-to-number (match-string 1 s)))
+            t t s)))
+  (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
+    (setq s (replace-match (concat "\\1"
+                                  (org-number-to-letters
+                                   (string-to-number (match-string 2 s))) "&")
+                          t nil s)))
+  s)
+
+(defun org-letters-to-number (s)
+  "Convert a base 26 number represented by letters into an integer.
+For example:  AB -> 28."
+  (let ((n 0))
+    (setq s (upcase s))
+    (while (> (length s) 0)
+         (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
+               s (substring s 1)))
+    n))
+
+(defun org-number-to-letters (n)
+  "Convert an integer into a base 26 number represented by letters.
+For example:  28 -> AB."
+  (let ((s ""))
+    (while (> n 0)
+      (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
+           n (/ (1- n) 26)))
+    s))
+
+(defun org-table-fedit-convert-buffer (function)
+  "Convert all references in this buffer, using FUNTION."
+  (let ((line (org-current-line)))
+    (goto-char (point-min))
+    (while (not (eobp))
+      (insert (funcall function (buffer-substring (point) (point-at-eol))))
+      (delete-region (point) (point-at-eol))
+      (or (eobp) (forward-char 1)))
+    (goto-line line)))
+
+(defun org-table-fedit-toggle-ref-type ()
+  "Convert all references in the buffer from B3 to @3$2 and back."
+  (interactive)
+  (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
+  (org-table-fedit-convert-buffer
+   (if org-table-buffer-is-an
+       'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
+  (message "Reference type switched to %s"
+          (if org-table-buffer-is-an "A1 etc" "@row$column")))
+
+(defun org-table-fedit-ref-up ()
+  "Shift the reference at point one row/hline up."
+  (interactive)
+  (org-table-fedit-shift-reference 'up))
+(defun org-table-fedit-ref-down ()
+  "Shift the reference at point one row/hline down."
+  (interactive)
+  (org-table-fedit-shift-reference 'down))
+(defun org-table-fedit-ref-left ()
+  "Shift the reference at point one field to the left."
+  (interactive)
+  (org-table-fedit-shift-reference 'left))
+(defun org-table-fedit-ref-right ()
+  "Shift the reference at point one field to the right."
+  (interactive)
+  (org-table-fedit-shift-reference 'right))
+
+(defun org-table-fedit-shift-reference (dir)
+  (cond
+   ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
+    (if (memq dir '(left right))
+       (org-rematch-and-replace 1 (eq dir 'left))
+      (error "Cannot shift reference in this direction")))
+   ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
+    ;; A B3-like reference
+    (if (memq dir '(up down))
+       (org-rematch-and-replace 2 (eq dir 'up))
+      (org-rematch-and-replace 1 (eq dir 'left))))
+   ((org-at-regexp-p
+     
"\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
+    ;; An internal reference
+    (if (memq dir '(up down))
+       (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
+      (org-rematch-and-replace 5 (eq dir 'left))))))
+
+(defun org-rematch-and-replace (n &optional decr hline)
+  "Re-match the group N, and replace it with the shifted refrence."
+  (or (match-end n) (error "Cannot shift reference in this direction"))
+  (goto-char (match-beginning n))
+  (and (looking-at (regexp-quote (match-string n)))
+       (replace-match (org-shift-refpart (match-string 0) decr hline)
+                     t t)))
+
+(defun org-shift-refpart (ref &optional decr hline)
+  "Shift a refrence part REF.
+If DECR is set, decrease the references row/column, else increase.
+If HLINE is set, this may be a hline reference, it certainly is not
+a translation reference."
+  (save-match-data
+    (let* ((sign (string-match "^[-+]" ref)) n)
+
+      (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
+      (cond
+       ((and hline (string-match "^I+" ref))
+       (setq n (string-to-number (concat sign (number-to-string (length 
ref)))))
+       (setq n (+ n (if decr -1 1)))
+       (if (= n 0) (setq n (+ n (if decr -1 1))))
+       (if sign
+           (setq sign (if (< n 0) "-" "+") n (abs n))
+         (setq n (max 1 n)))
+       (concat sign (make-string n ?I)))
+
+       ((string-match "^[0-9]+" ref)
+       (setq n (string-to-number (concat sign ref)))
+       (setq n (+ n (if decr -1 1)))
+       (if sign
+           (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
+         (number-to-string (max 1 n))))
+
+       ((string-match "^[a-zA-Z]+" ref)
+       (org-number-to-letters
+        (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
+
+       (t (error "Cannot shift reference"))))))
+
+(defun org-table-fedit-toggle-coordinates ()
+  "Toggle the display of coordinates in the refrenced table."
+  (interactive)
+  (let ((pos (marker-position org-pos)))
+    (with-current-buffer (marker-buffer org-pos)
+      (save-excursion
+       (goto-char pos)
+       (org-table-toggle-coordinate-overlays)))))
+
+(defun org-table-fedit-finish (&optional arg)
+  "Parse the buffer for formula definitions and install them.
+With prefix ARG, apply the new formulas to the table."
+  (interactive "P")
+  (org-table-remove-rectangle-highlight)
+  (if org-table-use-standard-references
+      (progn
+       (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
+       (setq org-table-buffer-is-an nil)))
+  (let ((pos org-pos) eql var form)
+    (goto-char (point-min))
+    (while (re-search-forward
+           "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ 
\t]+.*$\\)*\\)"
+           nil t)
+      (setq var (if (match-end 2) (match-string 2) (match-string 1))
+           form (match-string 3))
+      (setq form (org-trim form))
+      (when (not (equal form ""))
+       (while (string-match "[ \t]*\n[ \t]*" form)
+         (setq form (replace-match " " t t form)))
+       (when (assoc var eql)
+         (error "Double formulas for %s" var))
+       (push (cons var form) eql)))
+    (setq org-pos nil)
+    (set-window-configuration org-window-configuration)
+    (select-window (get-buffer-window (marker-buffer pos)))
+    (goto-char pos)
+    (unless (org-at-table-p)
+      (error "Lost table position - cannot install formulae"))
+    (org-table-store-formulas eql)
+    (move-marker pos nil)
+    (kill-buffer "*Edit Formulas*")
+    (if arg
+       (org-table-recalculate 'all)
+      (message "New formulas installed - press C-u C-c C-c to apply."))))
 
-(defun org-abort-edit-formulas ()
+(defun org-table-fedit-abort ()
   "Abort editing formulas, without installing the changes."
   (interactive)
   (org-table-remove-rectangle-highlight)
@@ -8023,7 +8758,7 @@
     (move-marker pos nil)
     (message "Formula editing aborted without installing changes")))
 
-(defun org-edit-formula-lisp-indent ()
+(defun org-table-fedit-lisp-indent ()
   "Pretty-print and re-indent Lisp expressions in the Formula Editor."
   (interactive)
   (let ((pos (point)) beg end ind)
@@ -8064,7 +8799,7 @@
 
 (defvar org-show-positions nil)
 
-(defun org-show-reference (&optional local)
+(defun org-table-show-reference (&optional local)
   "Show the location/value of the $ expression at point."
   (interactive)
   (org-table-remove-rectangle-highlight)
@@ -8077,12 +8812,18 @@
          var name e what match dest)
       (if local (org-table-get-specials))
       (setq what (cond
-                 ((org-at-regexp-p org-table-range-regexp2) 'range)
+                 ((or (org-at-regexp-p org-table-range-regexp2)
+                      (org-at-regexp-p org-table-translate-regexp)
+                      (org-at-regexp-p org-table-range-regexp))
+                  (setq match
+                        (save-match-data
+                          (org-table-convert-refs-to-rc (match-string 0))))
+                  'range)
                  ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
                  ((org-at-regexp-p "\\$[0-9]+") 'column)
                  ((not local) nil)
                  (t (error "No reference at point")))
-           match (and what (match-string 0)))
+           match (and what (or match (match-string 0))))
       (when (and  match (not (equal (match-beginning 0) (point-at-bol))))
        (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
                                         'secondary-selection))
@@ -8094,9 +8835,13 @@
        (setq match (org-table-formula-substitute-names match)))
       (unless local
        (save-excursion
+         (end-of-line 1)
+         (re-search-backward "^\\S-" nil t)
          (beginning-of-line 1)
-         (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\)=")
-           (setq dest (match-string 1))
+         (when (looking-at 
"\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
+           (setq dest
+                 (save-match-data
+                   (org-table-convert-refs-to-rc (match-string 1))))
            (org-table-add-rectangle-overlay
             (match-beginning 1) (match-end 1) face2))))
       (if (and (markerp pos) (marker-buffer pos))
@@ -8165,18 +8910,20 @@
          (message "Constant: $%s=%s in `org-table-formula-constants'."
                   var (cdr e)))
         ((setq e (and (fboundp 'constants-get) (constants-get var)))
-         (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
+         (message "Constant: $%s=%s, from `constants.el'%s."
+                  var e (format " (%s units)" constants-unit-system)))
         (t (error "Undefined name $%s" var)))))
       (goto-char pos)
-      (when org-show-positions
+      (when (and org-show-positions
+                 (not (memq this-command '(org-table-fedit-scroll
+                                           org-table-fedit-scroll-down))))
        (push pos org-show-positions)
+       (push org-table-current-begin-pos org-show-positions)
        (let ((min (apply 'min org-show-positions))
              (max (apply 'max org-show-positions)))
-         (when (or (not (pos-visible-in-window-p min))
-                   (not (pos-visible-in-window-p max)))
-           (goto-char min)
-           (set-window-start (selected-window) (point-at-bol))
-           (goto-char pos))))
+          (goto-char min) (recenter 0)
+          (goto-char max)
+          (or (pos-visible-in-window-p max) (recenter -1))))
       (select-window win))))
 
 (defun org-table-force-dataline ()
@@ -8193,27 +8940,17 @@
            ((or p1 p2) (goto-char (or p1 p2)))
            (t (error "No table dataline around here"))))))
 
-(defun org-table-edit-line-up ()
+(defun org-table-fedit-line-up ()
   "Move cursor one line up in the window showing the table."
   (interactive)
-  (org-table-edit-move 'previous-line))
+  (org-table-fedit-move 'previous-line))
 
-(defun org-table-edit-line-down ()
+(defun org-table-fedit-line-down ()
   "Move cursor one line down in the window showing the table."
   (interactive)
- (org-table-edit-move 'next-line))
-
-(defun org-table-edit-backward-field ()
-  "Move cursor one field backward in the window showing the table."
-  (interactive)
-  (org-table-edit-move 'org-table-previous-field))
-
-(defun org-table-edit-next-field ()
-  "Move cursor one field forward in the window showing the table."
-  (interactive)
-  (org-table-edit-move 'org-table-next-field))
+ (org-table-fedit-move 'next-line))
 
-(defun org-table-edit-move (command)
+(defun org-table-fedit-move (command)
   "Move the cursor in the window shoinw the table.
 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
   (let ((org-table-allow-automatic-line-recalculation nil)
@@ -8228,14 +8965,14 @@
     (move-marker pos (point))
     (select-window win)))
 
-(defun org-table-edit-scroll (N)
+(defun org-table-fedit-scroll (N)
   (interactive "p")
   (let ((other-window-scroll-buffer (marker-buffer org-pos)))
     (scroll-other-window N)))
 
-(defun org-table-edit-scroll-down (N)
+(defun org-table-fedit-scroll-down (N)
   (interactive "p")
-  (org-table-edit-scroll (- N)))
+  (org-table-fedit-scroll (- N)))
 
 (defvar org-table-rectangle-overlays nil)
        
@@ -8290,7 +9027,7 @@
   (mapc 'org-delete-overlay org-table-coordinate-overlays)
   (setq org-table-coordinate-overlays nil)
   (save-excursion
-    (let ((id 0) (ih 0) hline eol str ic ov beg)
+    (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
       (goto-char (org-table-begin))
       (while (org-at-table-p)
        (setq eol (point-at-eol))
@@ -8299,15 +9036,18 @@
        (setq hline (looking-at org-table-hline-regexp))
        (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
                    (format "%4d" (setq id (1+ id)))))
-       (org-overlay-before-string ov str 'org-formula 'evaporate)
+       (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
        (when hline
          (setq ic 0)
-         (while (re-search-forward "[+|]-+" eol t)
+         (while (re-search-forward "[+|]\\(-+\\)" eol t)
            (setq beg (1+ (match-beginning 0))
-                 str (concat "$" (int-to-string (setq ic (1+ ic)))))
+                 ic (1+ ic)
+                 s1 (concat "$" (int-to-string ic))
+                 s2 (org-number-to-letters ic)
+                 str (if (eq org-table-use-standard-references t) s2 s1))
            (setq ov (org-make-overlay beg (+ beg (length str))))
            (push ov org-table-coordinate-overlays)
-           (org-overlay-display ov str 'org-formula 'evaporate)))
+           (org-overlay-display ov str 'org-special-keyword 'evaporate)))
        (beginning-of-line 2)))))
 
 (defun org-table-toggle-coordinate-overlays ()
@@ -8492,7 +9232,7 @@
          '("\C-c}"              org-table-toggle-coordinate-overlays)
          '("\C-c{"              org-table-toggle-formula-debugger)
          '("\C-m"               org-table-next-row)
-         (list (org-key 'S-return) 'org-table-copy-down)
+         '([(shift return)]     org-table-copy-down)
          '("\C-c\C-q"           org-table-wrap-region)
          '("\C-c?"              org-table-field-info)
          '("\C-c "              org-table-blank-field)
@@ -8507,34 +9247,34 @@
        elt key fun cmd)
     (while (setq elt (pop bindings))
       (setq nfunc (1+ nfunc))
-      (setq key (car elt)
+      (setq key (org-key (car elt))
            fun (nth 1 elt)
            cmd (orgtbl-make-binding fun nfunc key))
-      (define-key orgtbl-mode-map key cmd))
+      (org-defkey orgtbl-mode-map key cmd))
 
     ;; Special treatment needed for TAB and RET
-    (define-key orgtbl-mode-map [(return)]
+    (org-defkey orgtbl-mode-map [(return)]
       (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
-    (define-key orgtbl-mode-map "\C-m"
+    (org-defkey orgtbl-mode-map "\C-m"
       (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
 
-    (define-key orgtbl-mode-map [(tab)]
+    (org-defkey orgtbl-mode-map [(tab)]
       (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
-    (define-key orgtbl-mode-map "\C-i"
+    (org-defkey orgtbl-mode-map "\C-i"
       (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
 
-    (define-key orgtbl-mode-map [(shift tab)]
+    (org-defkey orgtbl-mode-map [(shift tab)]
       (orgtbl-make-binding 'org-table-previous-field 104
                           [(shift tab)] [(tab)] "\C-i"))
 
-    (define-key orgtbl-mode-map "\M-\C-m"
+    (org-defkey orgtbl-mode-map "\M-\C-m"
       (orgtbl-make-binding 'org-table-wrap-region 105
                           "\M-\C-m" [(meta return)]))
-    (define-key orgtbl-mode-map [(meta return)]
+    (org-defkey orgtbl-mode-map [(meta return)]
       (orgtbl-make-binding 'org-table-wrap-region 106
                           [(meta return)] "\M-\C-m"))
 
-    (define-key orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
+    (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
     (when orgtbl-optimized
       ;; If the user wants maximum table support, we need to hijack
       ;; some standard editing functions
@@ -8542,7 +9282,7 @@
                 'self-insert-command 'orgtbl-self-insert-command
                 'delete-char 'org-delete-char
                 'delete-backward-char 'org-delete-backward-char)
-      (define-key orgtbl-mode-map "|" 'org-force-self-insert))
+      (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
     (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
       '("OrgTbl"
        ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
@@ -8678,7 +9418,31 @@
 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
   "Regula expression matching exponentials as produced by calc.")
 
-(defvar org-table-clean-did-remove-column-1 nil)
+(defvar org-table-clean-did-remove-column nil)
+
+(defun orgtbl-export (table target)
+  (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
+       (lines (org-split-string table "[ \t]*\n[ \t]*"))
+       org-table-last-alignment org-table-last-column-widths
+       maxcol column)
+    (if (not (fboundp func))
+       (error "Cannot export orgtbl table to %s" target))
+    (setq lines (org-table-clean-before-export lines))
+    (setq table
+         (mapcar
+          (lambda (x)
+            (if (string-match org-table-hline-regexp x)
+                'hline
+              (org-split-string (org-trim x) "\\s-*|\\s-*")))
+          lines))
+    (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
+                                    table)))
+    (loop for i from (1- maxcol) downto 0 do
+         (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
+         (setq column (delq nil column))
+         (push (apply 'max (mapcar 'string-width column)) 
org-table-last-column-widths)
+         (push (> (/ (apply '+ (mapcar (lambda (x) (if (string-match 
org-table-number-regexp x) 1 0)) column)) maxcol) org-table-number-fraction) 
org-table-last-alignment))
+    (funcall func table nil)))
 
 (defun orgtbl-send-table (&optional maybe)
   "Send a tranformed version of this table to the receiver position.
@@ -8706,7 +9470,7 @@
                 (org-table-begin) (org-table-end)))
           (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
           (lines (org-table-clean-before-export lines))
-          (i0 (if org-table-clean-did-remove-column-1 2 1))
+          (i0 (if org-table-clean-did-remove-column 2 1))
           (table (mapcar
                   (lambda (x)
                     (if (string-match org-table-hline-regexp x)
@@ -9430,7 +10194,8 @@
 With three \\[universal-argument] prefixes, negate the meaning of
 `org-keep-stored-link-after-insertion'."
   (interactive "P")
-  (let ((region (if (org-region-active-p)
+  (let ((wcf (current-window-configuration))
+       (region (if (org-region-active-p)
                    (prog1 (buffer-substring (region-beginning) (region-end))
                      (delete-region (region-beginning) (region-end)))))
         tmphist ; byte-compile incorrectly complains about this
@@ -9469,13 +10234,31 @@
         (t (setq link (org-make-link "file:" file))))))
      (t
       ;; Read link, with completion for stored links.
-      ;; Fake a link history
+      (with-output-to-temp-buffer "*Org Links*"
+       (princ "Insert a link.  Use TAB to complete valid link prefixes.\n")
+       (when org-stored-links
+         (princ "\nStored links ar available with <up>/<down> (most recent 
with RET):\n\n")
+         (princ (mapconcat 'car (reverse org-stored-links) "\n"))))
+      (let ((cw (selected-window)))
+       (select-window (get-buffer-window "*Org Links*"))
+       (shrink-window-if-larger-than-buffer)
+       (setq truncate-lines t)
+       (select-window cw))
+      ;; Fake a link history, containing the stored links.
       (setq tmphist (append (mapcar 'car org-stored-links)
                            org-insert-link-history))
+      (unwind-protect
       (setq link (org-completing-read
-                 "Link: " org-stored-links nil nil nil
+                     "Link: "
+                     (append
+                      (mapcar (lambda (x) (concat (car x) ":"))
+                              (append org-link-abbrev-alist-local 
org-link-abbrev-alist))
+                      (mapcar (lambda (x) (concat x ":")) org-link-types))
+                     nil nil nil
                  'tmphist
                  (or (car (car org-stored-links)))))
+       (set-window-configuration wcf)
+       (kill-buffer "*Org Links*"))
       (setq entry (assoc link org-stored-links))
       (or entry (push link org-insert-link-history))
       (if (funcall (if (equal complete-file '(64)) 'not 'identity)
@@ -9531,7 +10314,7 @@
 (defun org-completing-read (&rest args)
   (let ((minibuffer-local-completion-map
         (copy-keymap minibuffer-local-completion-map)))
-    (define-key minibuffer-local-completion-map " " 'self-insert-command)
+    (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
     (apply 'completing-read args)))
 
 ;;; Opening/following a link
@@ -9637,7 +10420,7 @@
            (setq type (match-string 1) path (match-string 2))
            (throw 'match t)))
        (save-excursion
-         (when (org-in-regexp "\\(:address@hidden:]+\\):[ \t\r\n]")
+         (when (org-in-regexp "\\(:address@hidden:]+\\):[ \t]*$")
            (setq type "tags"
                  path (match-string 1))
            (while (string-match ":" path)
@@ -9830,6 +10613,10 @@
 in all files.  If AVOID-POS is given, ignore matches near that position."
   (let ((case-fold-search t)
        (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
+       (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
+                                           (append '((" ") ("\t") ("\n"))
+                                                   org-emphasis-alist)
+                                           "\\|") "\\)"))
        (pos (point))
        (pre "") (post "")
        words re0 re1 re2 re3 re4 re5 re2a reall)
@@ -9866,7 +10653,8 @@
       ;; Make a series of regular expressions to find a match
       (setq words (org-split-string s "[ \n\r\t]+")
            re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
-           re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") 
"\\)[ \t\r\n]")
+           re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
+                       "\\)" markers)
            re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ 
\t\r\n]+") "\\)[ \t\r\n]")
            re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words 
"[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
            re1 (concat pre re2 post)
@@ -9908,16 +10696,18 @@
   (let ((m org-open-link-marker))
     (catch 'exit
       (while (apply 're-search-forward args)
+       (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
        (goto-char (match-end group))
        (if (and (or (not (eq (marker-buffer m) (current-buffer)))
                     (> (match-beginning 0) (marker-position m))
                     (< (match-end 0) (marker-position m)))
                 (save-match-data
-                  (or (not (org-in-regexp org-bracket-link-analytic-regexp 1))
+                    (or (not (org-in-regexp
+                              org-bracket-link-analytic-regexp 1))
                       (not (match-end 4))  ; no description
                       (and (<= (match-beginning 4) (point))
                            (>= (match-end 4) (point))))))
-                (throw 'exit (point)))))))
+             (throw 'exit (point))))))))
 
 (defun org-get-buffer-for-internal-link (buffer)
   "Return a buffer to be used for displaying the link target of internal 
links."
@@ -10065,7 +10855,7 @@
   (funcall (cdr (assq 'gnus org-link-frame-setup)))
   (if gnus-other-frame-object (select-frame gnus-other-frame-object))
   (cond ((and group article)
-        (gnus-group-read-group 0 nil group)
+        (gnus-group-read-group 1 nil group)
         (gnus-summary-goto-article (string-to-number article) nil t))
        (group (gnus-group-jump-to-group group))))
 
@@ -10346,7 +11136,7 @@
        (if (stringp command)
            (setq cmd command)
          (setq cmd 'emacs))))
-    (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
+    (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
             (not (file-exists-p file))
             (not org-open-non-existing-files))
        (error "No such file: %s" file))
@@ -10380,10 +11170,6 @@
     org-file-apps-defaults-windowsnt)
    (t org-file-apps-defaults-gnu)))
 
-(defun org-expand-file-name (path)
-  "Replace special path abbreviations and expand the file name."
-  (expand-file-name path))
-
 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
 (defun org-file-remote-p (file)
   "Test whether FILE specifies a location on a remote system.
@@ -10569,7 +11355,7 @@
     (replace-match ""))
   (catch 'quit
     (let* ((txt (buffer-substring (point-min) (point-max)))
-          (fastp current-prefix-arg)
+          (fastp (equal current-prefix-arg '(4)))
           (file (if fastp org-default-notes-file (org-get-org-file)))
           (heading org-remember-default-headline)
           (visiting (org-find-base-buffer-visiting file))
@@ -10577,6 +11363,7 @@
           (org-startup-align-all-tables nil)
           (org-goto-start-pos 1)
           spos level indent reversed)
+      (setq current-prefix-arg nil)
       ;; Modify text so that it becomes a nice subtree which can be inserted
       ;; into an org tree.
       (let* ((lines (split-string txt "\n"))
@@ -10597,13 +11384,13 @@
       ;; Find the file
       (if (not visiting) (find-file-noselect file))
       (with-current-buffer (or visiting (get-file-buffer file))
-       (save-excursion (and (goto-char (point-min))
-                            (not (re-search-forward "^\\* " nil t))
-                            (insert "\n* Notes\n")))
-       (setq reversed (org-notes-order-reversed-p))
        (save-excursion
          (save-restriction
            (widen)
+           (and (goto-char (point-min))
+                (not (re-search-forward "^\\* " nil t))
+                (insert "\n* Notes\n"))
+           (setq reversed (org-notes-order-reversed-p))
 
            ;; Find the default location
            (when (and heading (stringp heading) (string-match "\\S-" heading))
@@ -10636,12 +11423,12 @@
                     (re-search-forward "^\\*" nil t)
                     (beginning-of-line 1)
                     (org-paste-subtree 1 txt)))
-                 ((and (org-on-heading-p nil) (not current-prefix-arg))
+                 ((and (org-on-heading-p t) (not current-prefix-arg))
                   ;; Put it below this entry, at the beg/end of the subtree
                   (org-back-to-heading t)
                   (setq level (funcall outline-level))
                   (if reversed
-                      (outline-end-of-heading)
+                      (outline-next-heading)
                     (org-end-of-subtree t))
                   (if (not (bolp)) (newline))
                   (beginning-of-line 1)
@@ -10649,7 +11436,9 @@
                  (t
                   ;; Put it right there, with automatic level determined by
                   ;; org-paste-subtree or from prefix arg
-                  (org-paste-subtree current-prefix-arg txt)))
+                  (org-paste-subtree
+                   (if (numberp current-prefix-arg) current-prefix-arg)
+                   txt)))
            (when remember-save-after-remembering
              (save-buffer)
              (if (not visiting) (kill-buffer (current-buffer)))))))))
@@ -10838,7 +11627,7 @@
                   ((string-match "\\`\\*+[ \t]*\\'"
                                  (buffer-substring (point-at-bol) beg))
                    (setq type :todo)
-                   (mapcar 'list org-todo-keywords))
+                   (mapcar 'list org-todo-keywords-1))
                   (searchhead
                    (setq type :searchhead)
                    (save-excursion
@@ -10926,6 +11715,8 @@
 'none             -> empty state
 \"\"(empty string)  -> switch to empty state
 'done             -> switch to DONE
+'nextset          -> switch to the next set of keywords
+'previousset      -> switch to the previous set of keywords
 \"WAITING\"         -> switch to the specified keyword, but only if it
                      really is a member of `org-todo-keywords'."
   (interactive "P")
@@ -10935,52 +11726,76 @@
     (or (looking-at (concat " +" org-todo-regexp " *"))
        (looking-at " *"))
     (let* ((this (match-string 1))
+          (head (org-get-todo-sequence-head this))
+          (ass (assoc head org-todo-kwd-alist))
+          (interpret (nth 1 ass))
+          (done-word (nth 3 ass))
+          (final-done-word (nth 4 ass))
           (last-state (or this ""))
           (completion-ignore-case t)
-          (member (member this org-todo-keywords))
+          (member (member this org-todo-keywords-1))
           (tail (cdr member))
           (state (cond
                   ((equal arg '(4))
                    ;; Read a state with completion
                    (completing-read "State: " (mapcar (lambda(x) (list x))
-                                                      org-todo-keywords)
+                                                      org-todo-keywords-1)
                                     nil t))
                   ((eq arg 'right)
                    (if this
                        (if tail (car tail) nil)
-                     (car org-todo-keywords)))
+                     (car org-todo-keywords-1)))
                   ((eq arg 'left)
-                   (if (equal member org-todo-keywords)
+                   (if (equal member org-todo-keywords-1)
                        nil
                      (if this
-                         (nth (- (length org-todo-keywords) (length tail) 2)
-                              org-todo-keywords)
-                       org-done-string)))
+                         (nth (- (length org-todo-keywords-1) (length tail) 2)
+                              org-todo-keywords-1)
+                       (org-last org-todo-keywords-1))))
                   (arg
-                   ;; user requests a specific state
+                   ;; user or caller requests a specific state
                    (cond
                     ((equal arg "") nil)
                     ((eq arg 'none) nil)
-                    ((eq arg 'done) (org-last org-todo-keywords))
-                    ((car (member arg org-todo-keywords)))
+                    ((eq arg 'done) (or done-word (car org-done-keywords)))
+                    ((eq arg 'nextset)
+                     (or (car (cdr (member head org-todo-heads)))
+                         (car org-todo-heads)))
+                    ((eq arg 'previousset)
+                     (let ((org-todo-heads (reverse org-todo-heads)))
+                       (or (car (cdr (member head org-todo-heads)))
+                           (car org-todo-heads))))
+                    ((car (member arg org-todo-keywords-1)))
                     ((nth (1- (prefix-numeric-value arg))
-                            org-todo-keywords))))
-                  ((null member) (car org-todo-keywords))
+                            org-todo-keywords-1))))
+                  ((null member) (or head (car org-todo-keywords-1)))
+                  ((equal this final-done-word) nil) ;; -> make empty
                   ((null tail) nil) ;; -> first entry
-                  ((eq org-todo-interpretation 'sequence)
+                  ((eq interpret 'sequence)
                    (car tail))
-                  ((memq org-todo-interpretation '(type priority))
+                  ((memq interpret '(type priority))
                    (if (eq this-command last-command)
                        (car tail)
-                     (if (> (length tail) 0) org-done-string nil)))
+                     (if (> (length tail) 0)
+                         (or done-word (car org-done-keywords))
+                       nil)))
                   (t nil)))
           (next (if state (concat " " state " ") " "))
           dostates)
       (replace-match next t t)
+      (unless head
+       (setq head (org-get-todo-sequence-head state)
+             ass (assoc head org-todo-kwd-alist)
+             interpret (nth 1 ass)
+             done-word (nth 3 ass)
+             final-done-word (nth 4 ass)))
+      (when (memq arg '(nextset previousset))
+       (message "Keyword set: %s"
+                (mapconcat 'identity (assoc state org-todo-sets) " ")))
       (setq org-last-todo-state-is-todo
-           (not (equal state org-done-string)))
-      (when org-log-done
-       (setq dostates (and (eq org-todo-interpretation 'sequence)
+           (not (member state org-done-keywords)))
+      (when (and org-log-done (not (memq arg '(nextset previousset))))
+       (setq dostates (and (eq interpret 'sequence)
                            (listp org-log-done) (memq 'state org-log-done)))
        (cond
         ((and state (not this))
@@ -10988,7 +11803,7 @@
          (and dostates (org-add-log-maybe 'state state 'findpos)))
         ((and state dostates)
          (org-add-log-maybe 'state state 'findpos))
-        ((equal state org-done-string)
+        ((member state org-done-keywords)
          ;; Planning info calls the note-setting command.
          (org-add-planning-info 'closed (org-current-time)
                                 (if (org-get-repeat) nil 'scheduled))
@@ -10996,8 +11811,10 @@
       ;; Fixup tag positioning
       (and org-auto-align-tags (org-set-tags nil t))
       (run-hooks 'org-after-todo-state-change-hook)
-      (and (equal state org-done-string) (org-auto-repeat-maybe))
-      ))
+      (and (member state org-done-keywords) (org-auto-repeat-maybe))
+      (if (and arg (not (member state org-done-keywords)))
+         (setq head (org-get-todo-sequence-head state)))
+      (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)))
   ;; Fixup cursor location if close to the keyword
   (if (and (outline-on-heading-p)
           (not (bolp))
@@ -11008,8 +11825,24 @@
        (goto-char (or (match-end 2) (match-end 1)))
        (just-one-space))))
 
+(defun org-get-todo-sequence-head (kwd)
+  "Return the head of the TODO sequence to which KWD belongs.
+If KWD is not set, check if there is a text property remembering the
+right sequence."
+  (let (p)
+    (cond
+     ((not kwd)
+      (or (get-text-property (point-at-bol) 'org-todo-head)
+         (progn
+           (setq p (next-single-property-change (point-at-bol) 'org-todo-head
+                                                nil (point-at-eol)))
+           (get-text-property p 'org-todo-head))))
+     ((not (member kwd org-todo-keywords-1))
+      (car org-todo-keywords-1))
+     (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
+
 (defun org-get-repeat ()
-  "Return the REPEAT statement of this entry."
+  "Check if tere is a deadline/schedule with repeater in this entry."
   (save-match-data
     (save-excursion
       (org-back-to-heading t)
@@ -11020,24 +11853,29 @@
 (defvar org-last-changed-timestamp)
 (defvar org-log-post-message)
 (defun org-auto-repeat-maybe ()
-  "Check if the current headline contains a REPEAT key.
-If yes, set TODO state back to what it was and change any SCHEDULED
-or DEADLINE times the new date.
+  "Check if the current headline contains a repeated deadline/schedule.
+If yes, set TODO state back to what it was and change the base date
+of repeating deadline/scheduled time stamps to new date.
 This function should be run in the `org-after-todo-state-change-hook'."
   ;; last-state is dynamically scoped into this function
-  (let ((repeat (org-get-repeat))
+  (let* ((repeat (org-get-repeat))
+        (aa (assoc last-state org-todo-kwd-alist))
+        (interpret (nth 1 aa))
+        (head (nth 2 aa))
+        (done-word (nth 3 aa))
        (whata '(("d" . day) ("m" . month) ("y" . year)))
        (msg "Entry repeats: ")
        (org-log-done)
-       re type n what start)
+        re type n what ts)
     (when repeat
-      (org-todo (if (eq 'org-todo-interpretation 'type)
-                   last-state
-                 (car org-todo-keywords)))
-      (unless (memq 'org-add-log-note (default-value 'post-command-hook))
+      (org-todo (if (eq interpret 'type) last-state head))
+      (when (and org-log-repeat
+                (not (memq 'org-add-log-note
+                           (default-value 'post-command-hook))))
        ;; Make sure a note is taken
        (let ((org-log-done '(done)))
-         (org-add-log-maybe 'done org-done-string 'findpos)))
+         (org-add-log-maybe 'done (or done-word (car org-done-keywords))
+                            'findpos)))
       (org-back-to-heading t)
       (org-add-planning-info nil nil 'closed)
       (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
@@ -11045,11 +11883,10 @@
       (while (re-search-forward
              re (save-excursion (outline-next-heading) (point)) t)
        (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
-             start 0)
-       (while (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" repeat start)
-         (setq start (match-end 0)
-               n (string-to-number (match-string 1 repeat))
-               what (match-string 2 repeat))
+             ts (match-string (if (match-end 2) 2 4)))
+       (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
+         (setq n (string-to-number (match-string 1 ts))
+               what (match-string 2 ts))
          (if (equal what "w") (setq n (* n 7) what "d"))
          (org-timestamp-change n (cdr (assoc what whata))))
        (setq msg (concat msg type org-last-changed-timestamp " ")))
@@ -11062,15 +11899,20 @@
 headlines above the match.
 With \\[universal-argument] prefix, also show the DONE entries.
 With a numeric prefix N, construct a sparse tree for the Nth element
-of `org-todo-keywords'."
+of `org-todo-keywords-1'."
   (interactive "P")
   (let ((case-fold-search nil)
        (kwd-re
         (cond ((null arg) org-not-done-regexp)
-              ((equal arg '(4)) org-todo-regexp)
-              ((<= (prefix-numeric-value arg) (length org-todo-keywords))
+              ((equal arg '(4))
+               (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
+                                           (mapcar 'list 
org-todo-keywords-1))))
+                 (concat "\\("
+                         (mapconcat 'identity (org-split-string kwd "|") "\\|")
+                         "\\)\\>")))
+              ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
                (regexp-quote (nth (1- (prefix-numeric-value arg))
-                                  org-todo-keywords)))
+                                  org-todo-keywords-1)))
               (t (error "Invalid prefix argument: %s" arg)))))
     (message "%d TODO entries found"
             (org-occur (concat "^" outline-regexp " +" kwd-re )))))
@@ -11143,8 +11985,10 @@
                   ((eq what 'deadline) org-deadline-string)
                   ((eq what 'closed) org-closed-string))
             " ")
-           (org-insert-time-stamp time 
-                                  (or org-time-was-given (eq what 'closed))
+           (org-insert-time-stamp
+            time
+            (or org-time-was-given
+                (and (eq what 'closed) org-log-done-with-time))
                                   (eq what 'closed))
            (end-of-line 1))
          (goto-char (point-min))
@@ -11163,6 +12007,7 @@
 The auto-repeater uses this.")
 
 (defun org-add-log-maybe (&optional purpose state findpos)
+  "Set up the post command hook to take a note."
   (save-excursion
     (when (and (listp org-log-done)
               (memq purpose org-log-done))
@@ -11221,6 +12066,7 @@
                                "")))))
       (if lines (setq note (concat note " \\\\")))
       (push note lines))
+    (when lines
     (save-excursion
       (set-buffer (marker-buffer org-log-note-marker))
       (save-excursion
@@ -11231,7 +12077,7 @@
        (setq ind (concat (buffer-substring (point-at-bol) (point)) "    "))
        (insert "  - " (pop lines))
        (while lines
-         (insert "\n" ind (pop lines))))))
+           (insert "\n" ind (pop lines)))))))
   (set-window-configuration org-log-note-window-configuration)
   (with-current-buffer (marker-buffer org-log-note-return-to)
     (goto-char org-log-note-return-to))
@@ -11264,7 +12110,8 @@
        (when (or (not callback)
                  (save-match-data (funcall callback)))
          (setq cnt (1+ cnt))
-         (org-highlight-new-match (match-beginning 0) (match-end 0))
+         (when org-highlight-sparse-tree-matches
+           (org-highlight-new-match (match-beginning 0) (match-end 0)))
          (org-show-context 'occur-tree))))
     (when org-remove-highlights-with-change
       (org-add-hook 'before-change-functions 'org-remove-occur-highlights
@@ -11342,7 +12189,7 @@
 
 ;;;; Priorities
 
-(defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
+(defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
   "Regular expression matching the priority indicator.")
 
 (defvar org-remove-priority-next-time nil)
@@ -11371,18 +12218,18 @@
        (setq current org-default-priority))
       (cond
        ((eq action 'set)
-       (message "Priority A-%c, SPC to remove: " org-lowest-priority)
+       (message "Priority %c-%c, SPC to remove: " org-highest-priority 
org-lowest-priority)
        (setq new (read-char-exclusive))
        (cond ((equal new ?\ ) (setq remove t))
-             ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
+             ((or (< (upcase new) org-highest-priority) (> (upcase new) 
org-lowest-priority))
               (error "Priority must be between `%c' and `%c'"
-                     ?A org-lowest-priority))))
+                     org-highest-priority org-lowest-priority))))
        ((eq action 'up)
        (setq new (1- current)))
        ((eq action 'down)
        (setq new (1+ current)))
        (t (error "Invalid action")))
-      (setq new (min (max ?A (upcase new)) org-lowest-priority))
+      (setq new (min (max org-highest-priority (upcase new)) 
org-lowest-priority))
       (setq news (format "%c" new))
       (if have
          (if remove
@@ -11419,15 +12266,14 @@
 inclusion.  When TODO-ONLY is non-nil, only lines with a TODO keyword
 are included in the output."
   (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
-                    (mapconcat 'regexp-quote
-                               (nreverse (cdr (reverse org-todo-keywords)))
-                               "\\|")
+                    (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
                     "\\>\\)\\)? *\\(.*?\\)\\(:address@hidden:]+:\\)?[ \t]*$"))
         (props (list 'face nil
                      'done-face 'org-done
                      'undone-face nil
                      'mouse-face 'highlight
                      'org-not-done-regexp org-not-done-regexp
+                     'org-todo-regexp org-todo-regexp
                      'keymap org-agenda-keymap
                      'help-echo
                      (format "mouse-2 or RET jump to org file %s"
@@ -11435,7 +12281,7 @@
         (case-fold-search nil)
          lspos
         tags tags-list tags-alist (llast 0) rtn level category i txt
-        todo marker entry)
+        todo marker entry priority)
     (save-excursion
       (goto-char (point-min))
       (when (eq action 'sparse-tree) (org-overview))
@@ -11462,7 +12308,7 @@
                (if org-use-tag-inheritance
                    (apply 'append (mapcar 'cdr tags-alist))
                  tags))
-         (when (and (or (not todo-only) todo)
+         (when (and (or (not todo-only) (member todo org-not-done-keywords))
                     (eval matcher)
                     (or (not org-agenda-skip-archived-trees)
                         (not (member org-archive-tag tags-list))))
@@ -11477,11 +12323,13 @@
                          (if org-tags-match-list-sublevels
                              (make-string (1- level) ?.) "")
                          (org-get-heading))
-                        category tags-list))
+                        category tags-list)
+                   priority (org-get-priority txt))
              (goto-char lspos)
              (setq marker (org-agenda-new-marker))
              (org-add-props txt props
-               'org-marker marker 'org-hd-marker marker 'org-category category)
+               'org-marker marker 'org-hd-marker marker 'org-category category
+               'priority priority 'type "tagsmatch")
              (push txt rtn))
            ;; if we are to skip sublevels, jump to end of subtree
            (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
@@ -11610,7 +12458,7 @@
     (if arg
        (save-excursion
          (goto-char (point-min))
-         (let (buffer-invisibility-spec)  ; Emacs 21 compatibility
+         (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
            (while (re-search-forward re nil t)
              (org-set-tags nil t)
              (end-of-line 1)))
@@ -11637,6 +12485,7 @@
        (while (string-match "[-+&]+" tags)
          ;; No boolean logic, just a list
          (setq tags (replace-match ":" t t tags))))
+
       (if (string-match "\\`[\t ]*\\'" tags)
           (setq tags "")
        (unless (string-match ":$" tags) (setq tags (concat tags ":")))
@@ -11728,7 +12577,7 @@
         (fwidth (+ maxlen 3 1 3))
         (ncol (/ (- (window-width) 4) fwidth))
         (i-face 'org-done)
-        (c-face 'org-tag)
+        (c-face 'org-todo)
         tg cnt e c char c1 c2 ntable tbl rtn
         ov-start ov-end ov-prefix
         (exit-after-next org-fast-tag-selection-single-key)
@@ -12014,9 +12863,9 @@
         (timestr (format-time-string
                   (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
         (prompt (concat (if prompt (concat prompt " ") "")
-                        (format "YYYY-MM-DD [%s]: " timestr)))
+                        (format "Date and/or time (default [%s]): " timestr)))
         ans (org-ans0 "") org-ans1 org-ans2 (deltadays 0)
-        second minute hour day month year tl wday wday1)
+        second minute hour day month year tl wday wday1 pm)
 
     (cond
      (from-string (setq ans from-string))
@@ -12027,44 +12876,43 @@
          (calendar-forward-day (- (time-to-days default-time)
                                   (calendar-absolute-from-gregorian
                                    (calendar-current-date))))
-         (org-eval-in-calendar nil)
+         (org-eval-in-calendar nil t)
          (let* ((old-map (current-local-map))
                 (map (copy-keymap calendar-mode-map))
                 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
-           (define-key map (kbd "RET") 'org-calendar-select)
-           (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
+           (org-defkey map (kbd "RET") 'org-calendar-select)
+           (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
              'org-calendar-select-mouse)
-           (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
+           (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
              'org-calendar-select-mouse)
-           (define-key minibuffer-local-map [(meta shift left)]
+           (org-defkey minibuffer-local-map [(meta shift left)]
              (lambda () (interactive)
                (org-eval-in-calendar '(calendar-backward-month 1))))
-           (define-key minibuffer-local-map [(meta shift right)]
+           (org-defkey minibuffer-local-map [(meta shift right)]
              (lambda () (interactive)
                (org-eval-in-calendar '(calendar-forward-month 1))))
-           (define-key minibuffer-local-map [(shift up)]
+           (org-defkey minibuffer-local-map [(shift up)]
              (lambda () (interactive)
                (org-eval-in-calendar '(calendar-backward-week 1))))
-           (define-key minibuffer-local-map [(shift down)]
+           (org-defkey minibuffer-local-map [(shift down)]
              (lambda () (interactive)
                (org-eval-in-calendar '(calendar-forward-week 1))))
-           (define-key minibuffer-local-map [(shift left)]
+           (org-defkey minibuffer-local-map [(shift left)]
              (lambda () (interactive)
                (org-eval-in-calendar '(calendar-backward-day 1))))
-           (define-key minibuffer-local-map [(shift right)]
+           (org-defkey minibuffer-local-map [(shift right)]
              (lambda () (interactive)
                (org-eval-in-calendar '(calendar-forward-day 1))))
-           (define-key minibuffer-local-map ">"
+           (org-defkey minibuffer-local-map ">"
              (lambda () (interactive)
                (org-eval-in-calendar '(scroll-calendar-left 1))))
-           (define-key minibuffer-local-map "<"
+           (org-defkey minibuffer-local-map "<"
              (lambda () (interactive)
                (org-eval-in-calendar '(scroll-calendar-right 1))))
            (unwind-protect
                (progn
                  (use-local-map map)
                  (setq org-ans0 (read-string prompt "" nil nil))
-;                (if (not (string-match "\\S-" org-ans0)) (setq org-ans0 nil))
                  ;; org-ans0: from prompt
                  ;; org-ans1: from mouse click
                  ;; org-ans2: from calendar motion
@@ -12077,9 +12925,9 @@
     (if (string-match "^[ \t]*[-+][0-9]+[ \t]*$" org-ans0)
        (setq deltadays (string-to-number ans) ans ""))
 
-    (if (string-match
+    ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
+    (when (string-match
         "^ 
*\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
-       (progn
          (setq year (if (match-end 2)
                         (string-to-number (match-string 2 ans))
                       (string-to-number (format-time-string "%Y")))
@@ -12087,7 +12935,20 @@
                day (string-to-number (match-string 4 ans)))
          (if (< year 100) (setq year (+ 2000 year)))
          (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
-                                  t nil ans))))
+                              t nil ans)))
+    ;; Help matching am/pm times, because `parse-time-string' does not do that.
+    ;; If there is a time with am/pm, and *no* time without it, we convert
+    ;; convert so that matching will be successful.
+    (when (and (not (string-match "[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" 
ans))
+              (string-match 
"\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
+      (setq hour (string-to-number (match-string 1 ans))
+           minute (if (match-end 3) (string-to-number (match-string 3 ans)) 0)
+           pm (equal ?p (string-to-char (downcase (match-string 4 ans)))))
+      (if (and (= hour 12) (not pm))
+         (setq hour 0)
+       (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
+      (setq ans (replace-match (format "%02d:%02d" hour minute) t t ans)))
+
     (setq tl (parse-time-string ans)
          year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
          month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
@@ -12113,18 +12974,28 @@
          (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
        (format "%04d-%02d-%02d" year month day)))))
 
-(defun org-eval-in-calendar (form)
+(defun org-eval-in-calendar (form &optional keepdate)
   "Eval FORM in the calendar window and return to current window.
 Also, store the cursor date in variable org-ans2."
   (let ((sw (selected-window)))
     (select-window (get-buffer-window "*Calendar*"))
     (eval form)
-    (when (calendar-cursor-to-date)
+    (when (and (not keepdate) (calendar-cursor-to-date))
       (let* ((date (calendar-cursor-to-date))
             (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
        (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
     (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
-    (select-window sw)))
+    (select-window sw)
+    ;; Update the prompt to show new default date
+    (save-excursion
+      (goto-char (point-min))
+      (when (and org-ans2
+                (re-search-forward "\\[[-0-9]+\\]" nil t)
+                (get-text-property (match-end 0) 'field))
+       (let ((inhibit-read-only t))
+         (replace-match (concat "[" org-ans2 "]") t t)
+         (add-text-properties (point-min) (1+ (match-end 0))
+                              (text-properties-at (1+ (point-min)))))))))
 
 (defun org-calendar-select ()
   "Return to `org-read-date' with the date currently selected.
@@ -12136,7 +13007,7 @@
       (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
     (if (active-minibuffer-window) (exit-minibuffer))))
 
-(defun org-insert-time-stamp (time &optional with-hm inactive pre post)
+(defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
   "Insert a date stamp for the date given by the internal TIME.
 WITH-HM means, use the stamp format that includes the time of the day.
 INACTIVE means use square brackets instead of angular ones, so that the
@@ -12149,6 +13020,10 @@
     (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
     (insert (or pre ""))
     (insert (setq stamp (format-time-string fmt time)))
+    (when extra
+      (backward-char 1)
+      (insert extra)
+      (forward-char 1))
     (insert (or post ""))
     stamp))
 
@@ -12175,17 +13050,22 @@
 
 (defun org-display-custom-time (beg end)
   "Overlay modified time stamp format over timestamp between BED and END."
-  (let* ((t1 (save-match-data
-              (org-parse-time-string (buffer-substring beg end) t)))
-        (w1 (- end beg))
-        (with-hm (and (nth 1 t1) (nth 2 t1)))
-        (tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats))
-        (time (org-fix-decoded-time t1))
-        (str (org-add-props
+  (let* ((ts (buffer-substring beg end))
+        t1 w1 with-hm tf time str w2 (off 0))
+    (save-match-data
+      (setq t1 (org-parse-time-string ts t))
+      (if (string-match " \\+[0-9]+[dwmy]\\'" ts)
+         (setq off (- (match-end 0) (match-beginning 0)))))
+    (setq end (- end off))
+    (setq w1 (- end beg)
+         with-hm (and (nth 1 t1) (nth 2 t1))
+         tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
+         time (org-fix-decoded-time t1)
+         str (org-add-props
                  (format-time-string
                   (substring tf 1 -1) (apply 'encode-time time))
-                 nil 'mouse-face 'highlight))
-        (w2 (length str)))
+                 nil 'mouse-face 'highlight)
+         w2 (length str))
     (if (not (= w2 w1))
        (add-text-properties (1+ beg) (+ 2 beg)
                             (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
@@ -12349,6 +13229,133 @@
 (defun org-time-string-to-time (s)
   (apply 'encode-time (org-parse-time-string s)))
 
+(defun org-time-string-to-absolute (s &optional daynr)
+  "Convert a time stamp to an absolute day number.
+If there is a specifyer for a cyclic time stamp, get the closest date to
+DATE."
+  (cond
+   ((and daynr (string-match "\\`%%\\((.*)\\)" s))
+    (if (org-diary-sexp-entry (match-string 1 s) "" date)
+       daynr
+      (+ daynr 1000)))
+   ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
+    (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
+                         (time-to-days (current-time))) (match-string 0 s)))
+   (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
+
+(defun org-calendar-holiday ()
+  "List of holidays, for Diary display in Org-mode."
+  (let ((hl (check-calendar-holidays date)))
+    (if hl (mapconcat 'identity hl "; "))))
+
+(defun org-diary-sexp-entry (sexp entry date)
+  "Process a SEXP diary ENTRY for DATE."
+  (let ((result (if calendar-debug-sexp
+                    (let ((stack-trace-on-error t))
+                      (eval (car (read-from-string sexp))))
+                  (condition-case nil
+                      (eval (car (read-from-string sexp)))
+                    (error
+                     (beep)
+                     (message "Bad sexp at line %d in %s: %s"
+                             (org-current-line)
+                             (buffer-file-name) sexp)
+                     (sleep-for 2))))))
+    (cond ((stringp result) result)
+         ((and (consp result)
+               (stringp (cdr result))) (cdr result))
+         (result entry)
+          (t nil))))
+
+(defun org-diary-to-ical-string (frombuf)
+  "FIXME"
+  (let* ((tmpdir (if (featurep 'xemacs)
+                    (temp-directory)
+                  temporary-file-directory))
+        (tmpfile (make-temp-name
+                  (expand-file-name "orgics" tmpdir)))
+        buf rtn b e)
+    (save-excursion
+      (set-buffer frombuf)
+      (icalendar-export-region (point-min) (point-max) tmpfile)
+      (setq buf (find-buffer-visiting tmpfile))
+      (set-buffer buf)
+      (goto-char (point-min))
+      (if (re-search-forward "^BEGIN:VEVENT" nil t)
+         (setq b (match-beginning 0)))
+      (goto-char (point-max))
+      (if (re-search-backward "^END:VEVENT" nil t)
+         (setq e (match-end 0)))
+      (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
+    (kill-buffer buf)
+    (kill-buffer frombuf)
+    (delete-file tmpfile)
+    rtn))
+
+(defun org-closest-date (start current change)
+  "Find the date closest to CURRENT that is consistent with START and CHANGE."
+  ;; Make the proper lists from the dates
+  (catch 'exit
+    (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
+         dn dw sday cday n1 n2
+         d m y y1 y2 date1 date2 nmonths nm ny m2)
+
+      (setq start (org-date-to-gregorian start)
+           current (org-date-to-gregorian current)
+           sday (calendar-absolute-from-gregorian start)
+           cday  (calendar-absolute-from-gregorian current))
+
+      (if (<= cday sday) (throw 'exit sday))
+
+      (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
+         (setq dn (string-to-number (match-string 1 change))
+               dw (cdr (assoc (match-string 2 change) a1)))
+       (error "Invalid change specifyer: %s" change))
+      (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
+      (cond
+       ((eq dw 'day)
+       (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
+             n2 (+ n1 dn)))
+       ((eq dw 'year)
+       (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
+       (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
+       (setq date1 (list m d y1)
+             n1 (calendar-absolute-from-gregorian date1)
+             date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
+             n2 (calendar-absolute-from-gregorian date2)))
+       ((eq dw 'month)
+       ;; approx number of month between the tow dates
+       (setq nmonths (floor (/ (- cday sday) 30.436875)))
+       ;; How often does dn fit in there?
+       (setq d (nth 1 start) m (car start) y (nth 2 start)
+             nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
+             m (+ m nm)
+             ny (floor (/ m 12))
+             y (+ y ny)
+             m (- m (* ny 12)))
+       (while (> m 12) (setq m (- m 12) y (1+ y)))
+       (setq n1 (calendar-absolute-from-gregorian (list m d y)))
+       (setq m2 (+ m dn) y2 y)
+       (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
+       (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
+       (while (< n2 cday)
+         (setq n1 n2 m m2 y y2)
+         (setq m2 (+ m dn) y2 y)
+         (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
+         (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
+
+      (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1))))
+
+(defun org-date-to-gregorian (date)
+  "Turn any specification of DATE into a gregorian date for the calendar."
+  (cond ((integerp date) (calendar-gregorian-from-absolute date))
+       ((and (listp date) (= (length date) 3)) date)
+       ((stringp date)
+        (setq date (org-parse-time-string date))
+        (list (nth 4 date) (nth 3 date) (nth 5 date)))
+       ((listp date)
+        (list (nth 4 date) (nth 3 date) (nth 5 date)))))
+
 (defun org-parse-time-string (s &optional nodefault)
   "Parse the standard Org-mode time string.
 This should be a lot faster than the normal `parse-time-string'.
@@ -12436,6 +13443,7 @@
   (let ((pos (point))
        with-hm inactive
        org-ts-what
+       extra
        ts time time0)
     (if (not (org-at-timestamp-p t))
        (error "Not at a timestamp"))
@@ -12445,12 +13453,13 @@
             (not (get-text-property (1- (point)) 'display)))
        (setq org-ts-what 'day))
     (setq org-ts-what (or what org-ts-what)
-         with-hm (<= (abs (- (cdr org-ts-lengths)
-                             (- (match-end 0) (match-beginning 0))))
-                     1)
          inactive (= (char-after (match-beginning 0)) ?\[)
          ts (match-string 0))
     (replace-match "")
+    (if (string-match " \\+[0-9]+[dwmy]" ts)
+       (setq extra (match-string 0 ts)))
+    (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
+       (setq with-hm t))
     (setq time0 (org-parse-time-string ts))
     (setq time
          (apply 'encode-time
@@ -12476,7 +13485,7 @@
          (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
          (setq time (apply 'encode-time time0))))
     (setq org-last-changed-timestamp
-         (org-insert-time-stamp time with-hm inactive))
+         (org-insert-time-stamp time with-hm inactive nil nil extra))
     (org-clock-update-time-maybe)
     (goto-char pos)
     ;; Try to recenter the calendar window, if any
@@ -12525,8 +13534,27 @@
 
 ;;; The clock for measuring work time.
 
+(defvar org-mode-line-string "")
+(put 'org-mode-line-string 'risky-local-variable t)
+
+(defvar org-mode-line-timer nil)
+(defvar org-clock-heading "")
+(defvar org-clock-start-time "")
+
+(defun org-update-mode-line ()
+  (let* ((delta (- (time-to-seconds (current-time))
+                   (time-to-seconds org-clock-start-time)))
+        (h (floor delta 3600))
+        (m (floor (- delta (* 3600 h)) 60)))
+    (setq org-mode-line-string
+         (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
+                     'help-echo "Org-mode clock is running"))
+    (force-mode-line-update)))
+
 (defvar org-clock-marker (make-marker)
   "Marker recording the last clock-in.")
+(defvar org-clock-mode-line-entry nil
+  "Information for the modeline about the running clock.")
 
 (defun org-clock-in ()
   "Start the clock on the current item.
@@ -12536,6 +13564,10 @@
   (let (ts)
     (save-excursion
       (org-back-to-heading t)
+      (if (looking-at org-todo-line-regexp)
+         (setq org-clock-heading (match-string 3))
+       (setq org-clock-heading "???"))
+      (setq org-clock-heading (propertize org-clock-heading 'face nil))
       (beginning-of-line 2)
       (when (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
                 (not (equal (match-string 1) org-clock-string)))
@@ -12545,8 +13577,15 @@
       (insert "\n") (backward-char 1)
       (indent-relative)
       (insert org-clock-string " ")
+      (setq org-clock-start-time (current-time))
       (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
       (move-marker org-clock-marker (point) (buffer-base-buffer))
+      (or global-mode-string (setq global-mode-string '("")))
+      (or (memq 'org-mode-line-string global-mode-string)
+         (setq global-mode-string
+               (append global-mode-string '(org-mode-line-string))))
+      (org-update-mode-line)
+      (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
       (message "Clock started at %s" ts))))
 
 (defun org-clock-out (&optional fail-quietly)
@@ -12577,6 +13616,12 @@
       (insert " => " (format "%2d:%02d" h m))
       (move-marker org-clock-marker nil)
       (org-add-log-maybe 'clock-out)
+      (when org-mode-line-timer
+       (cancel-timer org-mode-line-timer)
+       (setq org-mode-line-timer nil))
+      (setq global-mode-string
+           (delq 'org-mode-line-string global-mode-string))
+      (force-mode-line-update)
       (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
 
 (defun org-clock-cancel ()
@@ -12704,7 +13749,7 @@
 (defun org-clock-out-if-current ()
   "Clock out if the current entry contains the running clock.
 This is used to stop the clock after a TODO entry is marked DONE."
-  (when (and (equal state org-done-string)
+  (when (and (member state org-done-keywords)
             (equal (marker-buffer org-clock-marker) (current-buffer))
             (< (point) org-clock-marker)
             (> (save-excursion (outline-next-heading) (point))
@@ -12984,86 +14029,89 @@
 
 (substitute-key-definition 'undo 'org-agenda-undo
                           org-agenda-mode-map global-map)
-(define-key org-agenda-mode-map "\C-i"     'org-agenda-goto)
-(define-key org-agenda-mode-map [(tab)]    'org-agenda-goto)
-(define-key org-agenda-mode-map "\C-m"     'org-agenda-switch-to)
-(define-key org-agenda-mode-map "\C-k"     'org-agenda-kill)
-(define-key org-agenda-mode-map "\C-c$"    'org-agenda-archive)
-(define-key org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
-(define-key org-agenda-mode-map "$"        'org-agenda-archive)
-(define-key org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
-(define-key org-agenda-mode-map " "        'org-agenda-show)
-(define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
-(define-key org-agenda-mode-map "\C-c\C-xb" 
'org-agenda-tree-to-indirect-buffer)
-(define-key org-agenda-mode-map "b"        'org-agenda-tree-to-indirect-buffer)
-(define-key org-agenda-mode-map "o"        'delete-other-windows)
-(define-key org-agenda-mode-map "L"        'org-agenda-recenter)
-(define-key org-agenda-mode-map "t"        'org-agenda-todo)
-(define-key org-agenda-mode-map "a"        'org-agenda-toggle-archive-tag)
-(define-key org-agenda-mode-map ":"        'org-agenda-set-tags)
-(define-key org-agenda-mode-map "."        'org-agenda-goto-today)
-(define-key org-agenda-mode-map "d"        'org-agenda-day-view)
-(define-key org-agenda-mode-map "w"        'org-agenda-week-view)
-(define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
-(define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
-(define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
-(define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
-
-(define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
-(define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
-(define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
+(org-defkey org-agenda-mode-map "\C-i"     'org-agenda-goto)
+(org-defkey org-agenda-mode-map [(tab)]    'org-agenda-goto)
+(org-defkey org-agenda-mode-map "\C-m"     'org-agenda-switch-to)
+(org-defkey org-agenda-mode-map "\C-k"     'org-agenda-kill)
+(org-defkey org-agenda-mode-map "\C-c$"    'org-agenda-archive)
+(org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
+(org-defkey org-agenda-mode-map "$"        'org-agenda-archive)
+(org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
+(org-defkey org-agenda-mode-map " "        'org-agenda-show)
+(org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
+(org-defkey org-agenda-mode-map [(control shift right)] 
'org-agenda-todo-nextset)
+(org-defkey org-agenda-mode-map [(control shift left)]  
'org-agenda-todo-previousset)
+(org-defkey org-agenda-mode-map "\C-c\C-xb" 
'org-agenda-tree-to-indirect-buffer)
+(org-defkey org-agenda-mode-map "b"        'org-agenda-tree-to-indirect-buffer)
+(org-defkey org-agenda-mode-map "o"        'delete-other-windows)
+(org-defkey org-agenda-mode-map "L"        'org-agenda-recenter)
+(org-defkey org-agenda-mode-map "t"        'org-agenda-todo)
+(org-defkey org-agenda-mode-map "a"        'org-agenda-toggle-archive-tag)
+(org-defkey org-agenda-mode-map ":"        'org-agenda-set-tags)
+(org-defkey org-agenda-mode-map "."        'org-agenda-goto-today)
+(org-defkey org-agenda-mode-map "d"        'org-agenda-day-view)
+(org-defkey org-agenda-mode-map "w"        'org-agenda-week-view)
+(org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
+(org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
+(org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
+(org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
+
+(org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
+(org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
+(org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
-  (while l (define-key org-agenda-mode-map
+  (while l (org-defkey org-agenda-mode-map
             (int-to-string (pop l)) 'digit-argument)))
 
-(define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
-(define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
-(define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
-(define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
-(define-key org-agenda-mode-map "r" 'org-agenda-redo)
-(define-key org-agenda-mode-map "q" 'org-agenda-quit)
-(define-key org-agenda-mode-map "x" 'org-agenda-exit)
-(define-key org-agenda-mode-map "s" 'org-save-all-org-buffers)
-(define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
-(define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
-(define-key org-agenda-mode-map "n" 'next-line)
-(define-key org-agenda-mode-map "p" 'previous-line)
-(define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
-(define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
-(define-key org-agenda-mode-map "," 'org-agenda-priority)
-(define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
-(define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
-(define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
+(org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
+(org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
+(org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
+(org-defkey org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
+(org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
+(org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
+(org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
+(org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
+(org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
+(org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
+(org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
+(org-defkey org-agenda-mode-map "n" 'next-line)
+(org-defkey org-agenda-mode-map "p" 'previous-line)
+(org-defkey org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
+(org-defkey org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
+(org-defkey org-agenda-mode-map "," 'org-agenda-priority)
+(org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
+(org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
+(org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
 (eval-after-load "calendar"
-  '(define-key calendar-mode-map org-calendar-to-agenda-key
+  '(org-defkey calendar-mode-map org-calendar-to-agenda-key
      'org-calendar-goto-agenda))
-(define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
-(define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
-(define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
-(define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
-(define-key org-agenda-mode-map "h" 'org-agenda-holidays)
-(define-key org-agenda-mode-map "H" 'org-agenda-holidays)
-(define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
-(define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
-(define-key org-agenda-mode-map "O" 'org-agenda-clock-out)
-(define-key org-agenda-mode-map "X" 'org-agenda-clock-cancel)
-(define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
-(define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
-(define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
-(define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
-(define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
-(define-key org-agenda-mode-map [(right)] 'org-agenda-later)
-(define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
-(define-key org-agenda-mode-map "\C-c\C-x\C-c" 
'org-export-icalendar-combine-agenda-files)
+(org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
+(org-defkey org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
+(org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
+(org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
+(org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
+(org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
+(org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
+(org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
+(org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
+(org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
+(org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
+(org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
+(org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
+(org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
+(org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
+(org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
+(org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
+(org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 
'org-export-icalendar-combine-agenda-files)
 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
   "Local keymap for agenda entries from Org-mode.")
 
-(define-key org-agenda-keymap
+(org-defkey org-agenda-keymap
   (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
-(define-key org-agenda-keymap
+(org-defkey org-agenda-keymap
   (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
 (when org-agenda-mouse-1-follows-link
-  (define-key org-agenda-keymap [follow-link] 'mouse-face))
+  (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
   '("Agenda"
     ("Agenda Files")
@@ -13120,6 +14168,7 @@
       :style toggle :selected org-agenda-include-diary :active 
(org-agenda-check-type nil 'agenda)]
      ["Use Time Grid" org-agenda-toggle-time-grid
       :style toggle :selected org-agenda-use-time-grid :active 
(org-agenda-check-type nil 'agenda)])
+    ["Write view to file" org-write-agenda t]
     ["Rebuild buffer" org-agenda-redo t]
     ["Save all Org-mode Buffers" org-save-all-org-buffers t]
     "--"
@@ -13146,6 +14195,11 @@
   `(unless (get-text-property (point) 'org-protected)
      ,@body))
 
+(defmacro org-unmodified (&rest body)
+  "Execute body without changing buffer-modified-p."
+  `(set-buffer-modified-p
+    (prog1 (buffer-modified-p) ,@body)))
+
 (defmacro org-with-remote-undo (_buffer &rest _body)
   "Execute BODY while recording undo information in two buffers."
   (declare (indent 1) (debug t))
@@ -13230,7 +14284,8 @@
 m     Call `org-tags-view' to display headlines with tags matching
       a condition  (the user is prompted for the condition).
 M     Like `m', but select only TODO entries, no ordinary headlines.
-l     Create a timeeline for the current buffer.
+l     Create a timeline for the current buffer.
+e     Export views to associated files.
 
 More commands can be added by configuring the variable
 `org-agenda-custom-commands'.  In particular, specific tags and TODO keyword
@@ -13261,7 +14316,7 @@
                  (let ((header
 "Press key for an agenda command:
 --------------------------------         C   Configure custom agenda commands
-a   Agenda for current week or day
+a   Agenda for current week or day       e   Export agenda views
 t   List of all TODO entries             T   Entries with special TODO kwd
 m   Match a TAGS query                   M   Like m, but only TODO entries
 L   Timeline for current buffer          #   List stuck projects (!=configure)
@@ -13279,6 +14334,9 @@
                              '(face bold))
                          (cond
                           ((stringp type) type)
+                          ((eq type 'agenda) "Agenda for current week or day")
+                          ((eq type 'alltodo) "List of all TODO entries")
+                          ((eq type 'stuck) "List of stuck projects")
                           ((eq type 'todo) "TODO keyword")
                           ((eq type 'tags) "Tags query")
                           ((eq type 'tags-todo) "Tags (TODO)")
@@ -13333,6 +14391,13 @@
              (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
                    lprops (nth 3 entry))
              (cond
+              ((eq type 'agenda)
+               (org-let lprops '(org-agenda-list current-prefix-arg)))
+              ((eq type 'alltodo)
+               (org-let lprops '(org-todo-list current-prefix-arg)))
+              ((eq type 'stuck)
+               (org-let lprops '(org-agenda-list-stuck-projects
+                                 current-prefix-arg)))
               ((eq type 'tags)
                (org-let lprops '(org-tags-view current-prefix-arg match)))
               ((eq type 'tags-todo)
@@ -13353,13 +14418,14 @@
               ((fboundp type)
                (org-let lprops '(funcall type match)))
               (t (error "Invalid custom agenda command type %s" type))))
-         (org-run-agenda-series (cddr entry))))
+         (org-run-agenda-series (nth 1 entry) (cddr entry))))
        ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
        ((equal c ?a) (call-interactively 'org-agenda-list))
        ((equal c ?t) (call-interactively 'org-todo-list))
        ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
        ((equal c ?m) (call-interactively 'org-tags-view))
        ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
+       ((equal c ?e) (call-interactively 'org-store-agenda-views))
        ((equal c ?L)
        (unless restrict-ok
          (error "This is not an Org-mode file"))
@@ -13368,10 +14434,10 @@
        ((equal c ?!) (customize-variable 'org-stuck-projects))
        (t (error "Invalid key"))))))
 
-(defun org-run-agenda-series (series)
-  (org-prepare-agenda)
+(defun org-run-agenda-series (name series)
+  (org-prepare-agenda name)
   (let* ((org-agenda-multi t)
-        (redo (list 'org-run-agenda-series (list 'quote series)))
+        (redo (list 'org-run-agenda-series name (list 'quote series)))
         (cmds (car series))
         (gprops (nth 1 series))
         match ;; The byte compiler incorrectly complains about this.  Keep it!
@@ -13380,11 +14446,14 @@
       (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
       (cond
        ((eq type 'agenda)
-       (call-interactively 'org-agenda-list))
+       (org-let2 gprops lprops
+         '(call-interactively 'org-agenda-list)))
        ((eq type 'alltodo)
-       (call-interactively 'org-todo-list))
+       (org-let2 gprops lprops
+         '(call-interactively 'org-todo-list)))
        ((eq type 'stuck)
-       (call-interactively 'org-agenda-list-stuck-projects))
+       (org-let2 gprops lprops
+         '(call-interactively 'org-agenda-list-stuck-projects)))
        ((eq type 'tags)
        (org-let2 gprops lprops
                  '(org-tags-view current-prefix-arg match)))
@@ -13405,17 +14474,208 @@
 
 ;;;###autoload
 (defmacro org-batch-agenda (cmd-key &rest parameters)
-  "Run an agenda command in batch mode, send result to STDOUT.
-CMD-KEY is a string that is also a key in `org-agenda-custom-commands'.
+  "Run an agenda command in batch mode and send the result to STDOUT.
+If CMD-KEY is a string of length 1, it is used as a key in
+`org-agenda-custom-commands' and triggers this command.  If it is a
+longer string is is used as a tags/todo match string.
 Paramters are alternating variable names and values that will be bound
 before running the agenda command."
   (let (pars)
     (while parameters
       (push (list (pop parameters) (if parameters (pop parameters))) pars))
+    (if (> (length cmd-key) 1)
+       (eval (list 'let (nreverse pars)
+                   (list 'org-tags-view nil cmd-key)))
+      (flet ((read-char-exclusive () (string-to-char cmd-key)))
+       (eval (list 'let (nreverse pars) '(org-agenda nil)))))
+    (set-buffer "*Org Agenda*")
+    (princ (org-encode-for-stdout (buffer-string)))))
+
+(defun org-encode-for-stdout (string)
+  (if (fboundp 'encode-coding-string)
+      (encode-coding-string string buffer-file-coding-system)
+    string))
+
+(defvar org-agenda-info nil)
+
+;;;###autoload
+(defmacro org-batch-agenda-csv (cmd-key &rest parameters)
+  "Run an agenda command in batch mode and send the result to STDOUT.
+If CMD-KEY is a string of length 1, it is used as a key in
+`org-agenda-custom-commands' and triggers this command.  If it is a
+longer string is is used as a tags/todo match string.
+Paramters are alternating variable names and values that will be bound
+before running the agenda command.
+
+The output gives a line for each selected agenda item.  Each
+item is a list of comma-separated values, like this:
+
+category,head,type,todo,tags,date,time,extra,priority-l,priority-n
+
+category     The category of the item
+head         The headline, without TODO kwd, TAGS and PRIORITY
+type         The type of the agenda entry, can be
+                todo               selected in TODO match
+                tagsmatch          selected in tags match
+                diary              imported from diary
+                deadline           a deadline on given date
+                scheduled          scheduled on given date
+                timestamp          entry has timestamp on given date
+                closed             entry was closed on given date
+                upcoming-deadline  warning about deadline
+                past-scheduled     forwarded scheduled item
+                block              entry has date block including g. date
+todo         The todo keyword, if any
+tags         All tags including inherited ones, separated by colons
+date         The relevant date, like 2007-2-14
+time         The time, like 15:00-16:50
+extra        Sting with extra planning info
+priority-l   The priority letter if any was given
+priority-n   The computed numerical priority"
+
+  (let (pars)
+    (while parameters
+      (push (list (pop parameters) (if parameters (pop parameters))) pars))
+    (push (list 'org-agenda-remove-tags t) pars)
+    (if (> (length cmd-key) 1)
+       (eval (list 'let (nreverse pars)
+                   (list 'org-tags-view nil cmd-key)))
     (flet ((read-char-exclusive () (string-to-char cmd-key)))
-      (eval (list 'let (nreverse pars) '(org-agenda nil))))
+       (eval (list 'let (nreverse pars) '(org-agenda nil)))))
+    (set-buffer "*Org Agenda*")
+    (let* ((lines (org-split-string (buffer-string) "\n"))
+          line)
+      (while (setq line (pop lines))
+       (catch 'next
+         (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
+         (setq org-agenda-info
+               (org-fix-agenda-info (text-properties-at 0 line)))
+         (princ
+          (org-encode-for-stdout
+           (mapconcat 'org-agenda-export-csv-mapper
+                      '(org-category txt type todo tags date time-of-day extra
+                                     priority-letter priority)
+                     ",")))
+         (princ "\n"))))))
+
+(defun org-fix-agenda-info (props)
+  "FIXME"
+  (let (tmp re)
+    (when (setq tmp (plist-get props 'tags))
+      (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
+    (when (setq tmp (plist-get props 'date))
+      (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
+      (let ((calendar-date-display-form '(year "-" month "-" day)))
+       '((format "%4d, %9s %2s, %4s" dayname monthname day year))
+
+       (setq tmp (calendar-date-string tmp)))
+      (setq props (plist-put props 'date tmp)))
+    (when (setq tmp (plist-get props 'day))
+      (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
+      (let ((calendar-date-display-form '(year "-" month "-" day)))
+       (setq tmp (calendar-date-string tmp)))
+      (setq props (plist-put props 'day tmp)))
+    (when (setq tmp (plist-get props 'txt))
+      (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
+       (plist-put props 'priority-letter (match-string 1 tmp))
+       (setq tmp (replace-match "" t t tmp)))
+      (when (and (setq re (plist-get props 'org-todo-regexp))
+                (setq re (concat "\\`\\.*" re " ?"))
+                (string-match re tmp))
+       (plist-put props 'todo (match-string 1 tmp))
+       (setq tmp (replace-match "" t t tmp)))
+      (plist-put props 'txt tmp)))
+  props)
+
+(defun org-agenda-export-csv-mapper (prop)
+  (let ((res (plist-get org-agenda-info prop)))
+    (setq res
+         (cond
+          ((not res) "")
+          ((stringp res) res)
+          (t (prin1-to-string res))))
+    (while (string-match "," res)
+      (setq res (replace-match ";" t t res)))
+    (org-trim res)))
+
+
+;;;###autoload
+(defun org-store-agenda-views (&rest parameters)
+  (interactive)
+  (eval (list 'org-batch-store-agenda-views)))
+
+(defvar org-agenda-buffer-name)
+
+;; FIXME, why is this a macro?????
+;;;###autoload
+(defmacro org-batch-store-agenda-views (&rest parameters)
+  "Run all custom agenda commands that have a file argument."
+  (let ((cmds org-agenda-custom-commands)
+       (dir (default-directory))
+       pars cmd thiscmdkey files opts)
+    (while parameters
+      (push (list (pop parameters) (if parameters (pop parameters))) pars))
+    (setq pars (reverse pars))
+    (save-window-excursion
+      (while cmds
+       (setq cmd (pop cmds)
+             thiscmdkey (car cmd)
+             opts (nth 3 cmd)
+             files (org-last cmd))
+       (if (stringp files) (setq files (list files)))
+       (when files
+         (flet ((read-char-exclusive () (string-to-char thiscmdkey)))
+           (eval (list 'let (append org-agenda-exporter-settings opts pars)
+                       '(org-agenda nil))))
     (set-buffer "*Org Agenda*")
-    (princ (buffer-string))))
+         (while files
+           (eval (list 'let (append org-agenda-exporter-settings opts pars)
+                       (list 'org-write-agenda 
+                             (expand-file-name (pop files) dir) t)))))
+       (kill-buffer org-agenda-buffer-name)))))
+
+(defun org-write-agenda (file &optional nosettings)
+  "Write the current buffer (an agenda view) as a file.
+Depending on the extension of the file name, plain text (.txt),
+HTML (.html or .htm) or Postscript (.ps) is produced.
+If NOSETTINGS is given, do not scope the settings of
+`org-agenda-exporter-settings' into the export commands.  This is used when
+the settings have already been scoped and we do not wish to overrule other,
+higher priority settings."
+  (interactive "FWrite agenda to file: ")
+  (if (not (file-writable-p file))
+      (error "Cannot write agenda to file %s" file))
+  (cond
+   ((string-match "\\.html?\\'" file) (require 'htmlize))
+   ((string-match "\\.ps\\'" file) (require 'ps-print)))
+  (org-let (if nosettings nil org-agenda-exporter-settings)
+    '(save-excursion
+       (save-window-excursion
+        (cond
+         ((string-match "\\.html?\\'" file)
+          (set-buffer (htmlize-buffer (current-buffer)))
+
+          (when (and org-agenda-export-html-style
+                     (string-match "<style>" org-agenda-export-html-style))
+            ;; replace <style> section with org-agenda-export-html-style
+            (goto-char (point-min))
+            (kill-region (- (search-forward "<style") 6)
+                         (search-forward "</style>"))
+            (insert org-agenda-export-html-style))
+          (write-file file)
+          (kill-buffer (current-buffer))
+          (message "HTML written to %s" file))
+         ((string-match "\\.ps\\'" file)
+          (ps-print-buffer-with-faces file)
+          (message "Postscript written to %s" file))
+         (t
+          (let ((bs (buffer-string)))
+            (find-file file)
+            (insert bs)
+            (save-buffer 0)
+            (kill-buffer (current-buffer))
+            (message "Plain text written to %s" file))))))
+    (set-buffer org-agenda-buffer-name)))
 
 (defmacro org-no-read-only (&rest body)
   "Inhibit read-only for BODY."
@@ -13508,13 +14768,6 @@
       (find-file (car fs)))
     (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
 
-(defun org-agenda-file-to-end ()
-  "Move/add the current file to the end of the agenda file list.
-If the file is not present in the list, it is appended to the list.  If it is
-present, it is moved there."
-  (interactive)
-  (org-agenda-file-to-front 'to-end))
-
 (defun org-agenda-file-to-front (&optional to-end)
   "Move/add the current file to the top of the agenda file list.
 If the file is not present in the list, it is added to the front.  If it is
@@ -13578,7 +14831,10 @@
 (defvar org-agenda-multi nil)  ; dynammically scoped
 (defvar org-agenda-buffer-name "*Org Agenda*")
 (defvar org-pre-agenda-window-conf nil)
-(defun org-prepare-agenda ()
+(defvar org-agenda-name nil)
+(defun org-prepare-agenda (&optional name)
+  (setq org-todo-keywords-for-agenda nil)
+  (setq org-done-keywords-for-agenda nil)
   (if org-agenda-multi
       (progn
        (setq buffer-read-only nil)
@@ -13588,6 +14844,10 @@
        (narrow-to-region (point) (point-max)))
     (org-agenda-maybe-reset-markers 'force)
     (org-prepare-agenda-buffers (org-agenda-files))
+    (setq org-todo-keywords-for-agenda
+         (org-uniquify org-todo-keywords-for-agenda))
+    (setq org-done-keywords-for-agenda
+         (org-uniquify org-done-keywords-for-agenda))
     (let* ((abuf (get-buffer-create org-agenda-buffer-name))
           (awin (get-buffer-window abuf)))
       (cond
@@ -13605,7 +14865,9 @@
        (switch-to-buffer-other-window abuf))))
     (setq buffer-read-only nil)
     (erase-buffer)
-    (org-agenda-mode))
+    (org-agenda-mode)
+    (and name (not org-agenda-name)
+        (org-set-local 'org-agenda-name name)))
   (setq buffer-read-only nil))
 
 (defun org-finalize-agenda ()
@@ -13617,7 +14879,9 @@
        (goto-char (point-min))
        (while (org-activate-bracket-links (point-max))
          (add-text-properties (match-beginning 0) (match-end 0)
-                              '(face org-link))))
+                              '(face org-link)))
+       (unless org-agenda-with-colors
+         (remove-text-properties (point-min) (point-max) '(face nil))))
       (run-hooks 'org-finalize-agenda-hook))))
 
 (defun org-prepare-agenda-buffers (files)
@@ -13635,6 +14899,10 @@
          (set-buffer (org-get-agenda-file-buffer file))
          (widen)
          (setq bmp (buffer-modified-p))
+         (setq org-todo-keywords-for-agenda
+               (append org-todo-keywords-for-agenda org-todo-keywords-1))
+         (setq org-done-keywords-for-agenda
+               (append org-done-keywords-for-agenda org-done-keywords))
          (save-excursion
            (remove-text-properties (point-min) (point-max) pall)
            (when org-agenda-skip-archived-trees
@@ -13733,9 +15001,13 @@
   "Get the table of categories and positions in current buffer."
   (let (tbl)
     (save-excursion
+      (save-restriction
+       (widen)
       (goto-char (point-min))
-      (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil 
t)
-       (push (cons (point) (org-trim (match-string 2))) tbl)))
+       (while (re-search-forward "^#\\+CATEGORY:[ \t]*\\(.*\\)"
+                                 nil t)
+         (push (cons (match-beginning 1)
+                     (org-trim (match-string 1))) tbl))))
     tbl))
 
 (defun org-get-category (&optional pos)
@@ -13792,16 +15064,18 @@
        (setq day-numbers (delq nil (mapcar (lambda(x)
                                              (if (>= x today) x nil))
                                            day-numbers))))
-    (org-prepare-agenda)
+    (org-prepare-agenda (concat "Timeline " 
+                               (file-name-nondirectory buffer-file-name)))
     (if doclosed (push :closed args))
     (push :timestamp args)
+    (push :sexp args)
     (if dotodo (push :todo args))
     (while (setq d (pop day-numbers))
       (if (and (listp d) (eq (car d) :omitted))
          (progn
            (setq s (point))
            (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
-           (put-text-property s (1- (point)) 'face 'org-level-3))
+           (put-text-property s (1- (point)) 'face 'org-agenda-structure))
        (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
        (if (and (>= d today)
                 dopast
@@ -13824,7 +15098,7 @@
 ;            (insert (format-time-string org-agenda-date-format
 ;                                        (calendar-time-from-absolute d 0))
 ;                    "\n")
-             (put-text-property s (1- (point)) 'face 'org-level-3)
+             (put-text-property s (1- (point)) 'face 'org-agenda-structure)
              (put-text-property s (1- (point)) 'org-date-line t)
              (if (equal d today)
                  (put-text-property s (1- (point)) 'org-today t))
@@ -13936,7 +15210,7 @@
       (push (1+ (car day-numbers)) day-numbers)
       (setq ndays (1- ndays)))
     (setq day-numbers (nreverse day-numbers))
-    (org-prepare-agenda)
+    (org-prepare-agenda "Day/Week")
     (org-set-local 'org-starting-day (car day-numbers))
     (org-set-local 'org-include-all-loc include-all)
     (when (and (or include-all org-agenda-include-all-todo)
@@ -13953,11 +15227,12 @@
       (when rtnall
        (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
        (add-text-properties (point-min) (1- (point))
-                            (list 'face 'org-level-3))
+                            (list 'face 'org-agenda-structure))
        (insert (org-finalize-agenda-entries rtnall) "\n")))
     (setq s (point))
     (insert (if (= nd 7) "Week-" "Day-") "agenda:\n")
-    (add-text-properties s (1- (point)) (list 'face 'org-level-3))
+    (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
+                                             'org-date-line t))
     (while (setq d (pop day-numbers))
       (setq date (calendar-gregorian-from-absolute d)
            s (point))
@@ -13974,10 +15249,10 @@
          (if org-agenda-show-log
              (setq rtn (org-agenda-get-day-entries
                         file date
-                        :deadline :scheduled :timestamp :closed))
+                        :deadline :scheduled :timestamp :sexp :closed))
            (setq rtn (org-agenda-get-day-entries
                       file date
-                      :deadline :scheduled :timestamp)))
+                      :deadline :scheduled :sexp :timestamp)))
          (setq rtnall (append rtnall rtn))))
       (if org-agenda-include-diary
          (progn
@@ -13994,7 +15269,7 @@
 ; FIXME: this gives a timezone problem
 ;          (insert (format-time-string org-agenda-date-format
 ;                                      (calendar-time-from-absolute d 0)) "\n")
-           (put-text-property s (1- (point)) 'face 'org-level-3)
+           (put-text-property s (1- (point)) 'face 'org-agenda-structure)
            (put-text-property s (1- (point)) 'org-date-line t)
            (if todayp (put-text-property s (1- (point)) 'org-today t))
            (if rtnall (insert
@@ -14030,28 +15305,28 @@
 The prefix arg can be used to select a specific TODO keyword and limit
 the list to these.  When using \\[universal-argument], you will be prompted
 for a keyword.  A numeric prefix directly selects the Nth keyword in
-`org-todo-keywords'."
+`org-todo-keywords-1'."
   (interactive "P")
   (require 'calendar)
   (org-compile-prefix-format 'todo)
   (org-set-sorting-strategy 'todo)
+  (org-prepare-agenda "TODO")
   (let* ((today (time-to-days (current-time)))
         (date (calendar-gregorian-from-absolute today))
-        (kwds org-todo-keywords)
+        (kwds org-todo-keywords-for-agenda)
         (completion-ignore-case t)
         (org-select-this-todo-keyword
          (if (stringp arg) arg
            (and arg (integerp arg) (> arg 0)
-                 (nth (1- arg) org-todo-keywords))))
+                 (nth (1- arg) kwds))))
         rtn rtnall files file pos)
     (when (equal arg '(4))
       (setq org-select-this-todo-keyword
-           (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
-                            nil t)))
+           (completing-read "Keyword (or KWD1|K2D2|...): "
+                            (mapcar 'list kwds) nil nil)))
     (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
-    (org-prepare-agenda)
     (org-set-local 'org-last-arg arg)
-    (org-set-local 'org-todo-keywords kwds)
+;FIXME    (org-set-local 'org-todo-keywords-for-agenda kwds)
     (setq org-agenda-redo-command
          '(org-todo-list (or current-prefix-arg org-last-arg)))
     (setq files (org-agenda-files)
@@ -14063,23 +15338,25 @@
        (setq rtnall (append rtnall rtn))))
     (if org-agenda-overriding-header
        (insert (org-add-props (copy-sequence org-agenda-overriding-header)
-                   nil 'face 'org-level-3) "\n")
+                   nil 'face 'org-agenda-structure) "\n")
       (insert "Global list of TODO items of type: ")
       (add-text-properties (point-min) (1- (point))
-                          (list 'face 'org-level-3))
+                          (list 'face 'org-agenda-structure))
       (setq pos (point))
       (insert (or org-select-this-todo-keyword "ALL") "\n")
       (add-text-properties pos (1- (point)) (list 'face 'org-warning))
       (setq pos (point))
       (unless org-agenda-multi
-       (insert
-        "Available with `N r': (0)ALL "
-        (let ((n 0))
-          (mapconcat (lambda (x)
-                       (format "(%d)%s" (setq n (1+ n)) x))
-                     org-todo-keywords " "))
-        "\n"))
-      (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
+       (insert "Available with `N r': (0)ALL")
+       (let ((n 0) s)
+         (mapc (lambda (x)
+                 (setq s (format "(%d)%s" (setq n (1+ n)) x))
+                 (if (> (+ (current-column) (string-width s) 1) (frame-width))
+                     (insert "\n                    "))
+                 (insert " " s))
+               kwds))
+       (insert "\n"))
+      (add-text-properties pos (1- (point)) (list 'face 
'org-agenda-structure)))
     (when rtnall
       (insert (org-finalize-agenda-entries rtnall) "\n"))
     (goto-char (point-min))
@@ -14104,7 +15381,7 @@
         buffer)
     (setq matcher (org-make-tags-matcher match)
          match (car matcher) matcher (cdr matcher))
-    (org-prepare-agenda)
+    (org-prepare-agenda (concat "TAGS " match))
     (setq org-agenda-redo-command
          (list 'org-tags-view (list 'quote todo-only)
                (list 'if 'current-prefix-arg nil match)))
@@ -14135,17 +15412,17 @@
                (setq rtnall (append rtnall rtn))))))))
     (if org-agenda-overriding-header
        (insert (org-add-props (copy-sequence org-agenda-overriding-header)
-                   nil 'face 'org-level-3) "\n")
+                   nil 'face 'org-agenda-structure) "\n")
       (insert "Headlines with TAGS match: ")
       (add-text-properties (point-min) (1- (point))
-                          (list 'face 'org-level-3))
+                          (list 'face 'org-agenda-structure))
       (setq pos (point))
       (insert match "\n")
       (add-text-properties pos (1- (point)) (list 'face 'org-warning))
       (setq pos (point))
       (unless org-agenda-multi
        (insert "Press `C-u r' to search again with new search string\n"))
-      (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
+      (add-text-properties pos (1- (point)) (list 'face 
'org-agenda-structure)))
     (when rtnall
       (insert (org-finalize-agenda-entries rtnall) "\n"))
     (goto-char (point-min))
@@ -14187,21 +15464,34 @@
         (org-agenda-overriding-header "List of stuck projects: ")
         (matcher (nth 0 org-stuck-projects))
         (todo (nth 1 org-stuck-projects))
-        (tags (nth 2 org-stuck-projects))
+        (todo-wds (if (member "*" todo)
+                      (progn
+                        (org-prepare-agenda-buffers (org-agenda-files))
+                        (org-delete-all
+                         org-done-keywords-for-agenda
+                         (copy-sequence org-todo-keywords-for-agenda)))
+                    todo))
         (todo-re (concat "^\\*+[ \t]+\\("
-                         (mapconcat 'identity todo "\\|")
+                         (mapconcat 'identity todo-wds "\\|")
                          "\\)\\>"))
-        (tags-re (concat "^\\*+.*:\\("
+        (tags (nth 2 org-stuck-projects))
+        (tags-re (if (member "*" tags)
+                     "^\\*+.*:address@hidden:[ \t]*$"
+                   (concat "^\\*+.*:\\("
                          (mapconcat 'identity tags "\\|")
                          "\\):[a-zA-Z0-9_@:]*[ \t]*$")))
-
+        (gen-re (nth 3 org-stuck-projects))
+        (re-list
+         (delq nil
+               (list
+                (if todo todo-re)
+                (if tags tags-re)
+                (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
+                     gen-re)))))
     (setq org-agenda-skip-regexp
-         (cond
-          ((and todo tags)
-           (concat todo-re "\\|" tags-re))
-          (todo todo-re)
-          (tags tags-re)
-          (t (error "No information how to identify unstuck projects"))))
+         (if re-list
+             (mapconcat 'identity re-list "\\|")
+           (error "No information how to identify unstuck projects")))
     (org-tags-view nil matcher)
     (with-current-buffer org-agenda-buffer-name
       (setq org-agenda-redo-command
@@ -14247,7 +15537,8 @@
             (lambda (x)
               (setq x (org-format-agenda-item "" x "Diary" nil 'time))
               ;; Extend the text properties to the beginning of the line
-              (org-add-props x (text-properties-at (1- (length x)) x)))
+              (org-add-props x (text-properties-at (1- (length x)) x)
+                'type "diary" 'date date))
             entries)))))
 
 (defun org-agenda-cleanup-fancy-diary ()
@@ -14316,6 +15607,8 @@
                 date range matching the selected date.  Deadlines will
                 also be listed, on the expiration day.
 
+   :sexp         FIXME
+
    :deadline     List any deadlines past due, or due within
                 `org-deadline-warning-days'.  The listing occurs only
                 in the diary for *today*, not at any other date.  If
@@ -14340,10 +15633,10 @@
    &%%(org-diary)
 
 If you don't give any arguments (as in the example above), the default
-arguments (:deadline :scheduled :timestamp) are used.  So the example above may
-also be written as
+arguments (:deadline :scheduled :timestamp :sexp) are used.
+So the example above may also be written as
 
-   &%%(org-diary :deadline :timestamp :scheduled)
+   &%%(org-diary :deadline :timestamp :sexp :scheduled)
 
 The function expects the lisp variables `entry' and `date' to be provided
 by the caller, because this is how the calendar works.  Don't use this
@@ -14351,11 +15644,12 @@
   (org-agenda-maybe-reset-markers)
   (org-compile-prefix-format 'agenda)
   (org-set-sorting-strategy 'agenda)
-  (setq args (or args '(:deadline :scheduled :timestamp)))
+  (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
   (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
                    (list entry)
                  (org-agenda-files t)))
         file rtn results)
+    (org-prepare-agenda-buffers files)
     ;; If this is called during org-agenda, don't return any entries to
     ;; the calendar.  Org Agenda will list these entries itself.
     (if org-disable-agenda-to-diary (setq files nil))
@@ -14373,7 +15667,7 @@
 the one returned by `calendar-current-date'.  ARGS are symbols indicating
 which kind of entries should be extracted.  For details about these, see
 the documentation of `org-diary'."
-  (setq args (or args '(:deadline :scheduled :timestamp)))
+  (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
   (let* ((org-startup-folded nil)
         (org-startup-align-all-tables nil)
         (buffer (if (file-exists-p file)
@@ -14406,6 +15700,9 @@
                  (setq results (append results rtn))
                  (setq rtn (org-agenda-get-timestamps))
                  (setq results (append results rtn)))
+                ((eq arg :sexp)
+                 (setq rtn (org-agenda-get-sexps))
+                 (setq results (append results rtn)))
                 ((eq arg :scheduled)
                  (setq rtn (org-agenda-get-scheduled))
                  (setq results (append results rtn)))
@@ -14447,15 +15744,20 @@
   (let* ((props (list 'face nil
                      'done-face 'org-done
                      'org-not-done-regexp org-not-done-regexp
+                     'org-todo-regexp org-todo-regexp
                      'mouse-face 'highlight
                      'keymap org-agenda-keymap
                      'help-echo
                      (format "mouse-2 or RET jump to org file %s"
                              (abbreviate-file-name buffer-file-name))))
+        ;; FIXME: get rid of the \n at some point  but watch out
         (regexp (concat "[\n\r]\\*+ *\\("
                         (if org-select-this-todo-keyword
-                            (concat "\\<\\(" org-select-this-todo-keyword
-                                    "\\)\\>")
+                            (if (equal org-select-this-todo-keyword "*")
+                                org-todo-regexp
+                              (concat "\\<\\("
+                                      (mapconcat 'identity (org-split-string 
org-select-this-todo-keyword "|") "\\|")
+                                    "\\)\\>"))
                           org-not-done-regexp)
                         "[^\n\r]*\\)"))
         marker priority category tags
@@ -14481,16 +15783,11 @@
              category (org-get-category)
              tags (org-get-tags-at (point))
              txt (org-format-agenda-item "" (match-string 1) category tags)
-             priority
-             (+ (org-get-priority txt)
-                (if org-todo-kwd-priority-p
-                    (- org-todo-kwd-max-priority -2
-                       (length
-                        (member (match-string 2) org-todo-keywords)))
-                    1)))
+             priority (1+ (org-get-priority txt)))
        (org-add-props txt props
          'org-marker marker 'org-hd-marker marker
-         'priority priority 'org-category category)
+         'priority priority 'org-category category
+         'type "todo")
        (push txt ee)
        (if org-agenda-todo-list-sublevels
            (goto-char (match-end 1))
@@ -14504,38 +15801,61 @@
   "Return the date stamp information for agenda display."
   (let* ((props (list 'face nil
                      'org-not-done-regexp org-not-done-regexp
+                     'org-todo-regexp org-todo-regexp
                      'mouse-face 'highlight
                      'keymap org-agenda-keymap
                      'help-echo
                      (format "mouse-2 or RET jump to org file %s"
                              (abbreviate-file-name buffer-file-name))))
-        (regexp (regexp-quote
+;????   (regexp (regexp-quote
+;                (substring
+;                 (format-time-string
+;                  (car org-time-stamp-formats)
+;                  (apply 'encode-time  ; DATE bound by calendar
+;                         (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
+;                 0 11)))
+        (d1 (calendar-absolute-from-gregorian date))
+        (regexp
+         (concat
+          (regexp-quote
                  (substring
                   (format-time-string
                    (car org-time-stamp-formats)
                    (apply 'encode-time  ; DATE bound by calendar
                           (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
-                  0 11)))
+            0 11))
+          "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
+          "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
         marker hdmarker deadlinep scheduledp donep tmp priority category
-        ee txt timestr tags)
+        ee txt timestr tags b0 b3 e3)
     (goto-char (point-min))
     (while (re-search-forward regexp nil t)
+      (setq b0 (match-beginning 0)
+           b3 (match-beginning 3) e3 (match-end 3))
       (catch :skip
-       (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
+       (and (org-at-date-range-p) (throw :skip nil))
        (org-agenda-skip)
-       (setq marker (org-agenda-new-marker (match-beginning 0))
-             category (org-get-category (match-beginning 0))
+       (if (and (match-end 1)
+                (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
+           (throw :skip nil))
+       (if (and e3
+                (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
+           (throw :skip nil))
+       (setq marker (org-agenda-new-marker b0)
+             category (org-get-category b0)
              tmp (buffer-substring (max (point-min)
-                                        (- (match-beginning 0)
-                                           org-ds-keyword-length))
-                                   (match-beginning 0))
-             timestr (buffer-substring (match-beginning 0) (point-at-eol))
+                                        (- b0 org-ds-keyword-length))
+                                   b0)
+             timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
              deadlinep (string-match org-deadline-regexp tmp)
              scheduledp (string-match org-scheduled-regexp tmp)
              donep (org-entry-is-done-p))
        (and org-agenda-skip-scheduled-if-done
             scheduledp donep
             (throw :skip t))
+       (and org-agenda-skip-deadline-if-done
+            deadlinep donep
+            (throw :skip t))
        (if (string-match ">" timestr)
            ;; substring should only run to end of time stamp
            (setq timestr (substring timestr 0 (match-end 0))))
@@ -14558,22 +15878,68 @@
          (if deadlinep
              (org-add-props txt nil
                'face (if donep 'org-done 'org-warning)
+               'type "deadline" 'date date
                'undone-face 'org-warning 'done-face 'org-done
                'org-category category 'priority (+ 100 priority))
            (if scheduledp
                (org-add-props txt nil
                  'face 'org-scheduled-today
+                 'type "scheduled" 'date date
                  'undone-face 'org-scheduled-today 'done-face 'org-done
                  'org-category category 'priority (+ 99 priority))
-             (org-add-props txt nil 'priority priority 'org-category 
category)))
+             (org-add-props txt nil 'priority priority
+                            'org-category category 'date date
+                            'type "timestamp")))
          (push txt ee))
        (outline-next-heading)))
     (nreverse ee)))
 
+(defun org-agenda-get-sexps ()
+  "Return the sexp information for agenda display."
+  (require 'diary-lib)
+  (let* ((props (list 'face nil
+                     'mouse-face 'highlight
+                     'keymap org-agenda-keymap
+                     'help-echo
+                     (format "mouse-2 or RET jump to org file %s"
+                             (abbreviate-file-name buffer-file-name))))
+        (regexp "^&?%%(")
+        marker category ee txt tags entry result beg b sexp sexp-entry)
+    (goto-char (point-min))
+    (while (re-search-forward regexp nil t)
+      (catch :skip
+       (org-agenda-skip)
+       (setq beg (match-beginning 0))
+       (goto-char (1- (match-end 0)))
+       (setq b (point))
+       (forward-sexp 1)
+       (setq sexp (buffer-substring b (point)))
+       (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
+                            (org-trim (match-string 1))
+                          ""))
+       (setq result (org-diary-sexp-entry sexp sexp-entry date))
+       (when result
+         (setq marker (org-agenda-new-marker beg)
+               category (org-get-category beg))
+
+         (if (string-match "\\S-" result)
+             (setq txt result)
+           (setq txt "SEXP entry returned empty string"))
+
+         (setq txt (org-format-agenda-item
+                     "" txt category tags 'time))
+         (org-add-props txt props 'org-marker marker)
+         (org-add-props txt nil
+           'org-category category 'date date
+           'type "sexp")
+         (push txt ee))))
+    (nreverse ee)))
+
 (defun org-agenda-get-closed ()
   "Return the logged TODO entries for agenda display."
   (let* ((props (list 'mouse-face 'highlight
                      'org-not-done-regexp org-not-done-regexp
+                     'org-todo-regexp org-todo-regexp
                      'keymap org-agenda-keymap
                      'help-echo
                      (format "mouse-2 or RET jump to org file %s"
@@ -14617,6 +15983,7 @@
          (org-add-props txt props
            'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
            'priority priority 'org-category category
+           'type "closed" 'date date
            'undone-face 'org-warning 'done-face 'org-done)
          (push txt ee))
        (outline-next-heading)))
@@ -14627,6 +15994,7 @@
   (let* ((wdays org-deadline-warning-days)
         (props (list 'mouse-face 'highlight
                      'org-not-done-regexp org-not-done-regexp
+                     'org-todo-regexp org-todo-regexp
                      'keymap org-agenda-keymap
                      'help-echo
                      (format "mouse-2 or RET jump to org file %s"
@@ -14641,8 +16009,9 @@
       (catch :skip
        (org-agenda-skip)
        (setq pos (1- (match-beginning 1))
-             d2 (time-to-days
-                 (org-time-string-to-time (match-string 1)))
+;???         d2 (time-to-days
+;???             (org-time-string-to-time (match-string 1)))
+             d2 (org-time-string-to-absolute (match-string 1) d1)
              diff (- d2 d1))
        ;; When to show a deadline in the calendar:
        ;; If the expiration is within wdays warning time.
@@ -14673,6 +16042,7 @@
                  'org-hd-marker (org-agenda-new-marker pos1)
                  'priority (+ (- 10 diff) (org-get-priority txt))
                  'org-category category
+                 'type "upcoming-deadline" 'date d2
                  'face face 'undone-face face 'done-face 'org-done)
                (push txt ee))))))
     ee))
@@ -14681,6 +16051,7 @@
   "Return the scheduled information for agenda display."
   (let* ((props (list 'face 'org-scheduled-previously
                      'org-not-done-regexp org-not-done-regexp
+                     'org-todo-regexp org-todo-regexp
                      'undone-face 'org-scheduled-previously
                      'done-face 'org-done
                      'mouse-face 'highlight
@@ -14698,8 +16069,9 @@
       (catch :skip
        (org-agenda-skip)
        (setq pos (1- (match-beginning 1))
-             d2 (time-to-days
-                 (org-time-string-to-time (match-string 1)))
+             d2 (org-time-string-to-absolute (match-string 1) d1)
+;???         d2 (time-to-days
+;???             (org-time-string-to-time (match-string 1)))
              diff (- d2 d1))
        ;; When to show a scheduled item in the calendar:
        ;; If it is on or past the date.
@@ -14724,6 +16096,7 @@
                (org-add-props txt props
                  'org-marker (org-agenda-new-marker pos)
                  'org-hd-marker (org-agenda-new-marker pos1)
+                 'type "past-scheduled" 'date d2
                  'priority (+ (- 5 diff) (org-get-priority txt))
                  'org-category category)
                (push txt ee))))))
@@ -14733,6 +16106,7 @@
   "Return the date-range information for agenda display."
   (let* ((props (list 'face nil
                      'org-not-done-regexp org-not-done-regexp
+                     'org-todo-regexp org-todo-regexp
                      'mouse-face 'highlight
                      'keymap org-agenda-keymap
                      'help-echo
@@ -14771,6 +16145,7 @@
                (setq txt org-agenda-no-heading-message))
              (org-add-props txt props
                'org-marker marker 'org-hd-marker hdmarker
+               'type "block" 'date date
                'priority (org-get-priority txt) 'org-category category)
              (push txt ee)))
        (goto-char pos)))
@@ -14865,8 +16240,8 @@
 
       (when (string-match "\\([ \t]+\\)\\(:address@hidden:]+:\\)[ \t]*$" txt)
        ;; Tags are in the string
-       (if (or (eq org-agenda-remove-tags-when-in-prefix t)
-               (and org-agenda-remove-tags-when-in-prefix
+       (if (or (eq org-agenda-remove-tags t)
+               (and org-agenda-remove-tags
                     org-prefix-has-tag))
            (setq txt (replace-match "" t t txt))
          (setq txt (replace-match
@@ -14891,9 +16266,12 @@
        'org-category (downcase category) 'tags tags
        'prefix-length (- (length rtn) (length txt))
        'time-of-day time-of-day
+       'txt txt
+       'time time
+       'extra extra
        'dotime dotime))))
 
-(defvar org-agenda-sorting-strategy)
+(defvar org-agenda-sorting-strategy) ;; FIXME: can be removed?
 (defvar org-agenda-sorting-strategy-selected nil)
 
 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
@@ -15243,6 +16621,7 @@
   "Detach overlay INDEX."
   (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
 
+;; FIXME this is currently not used.
 (defun org-highlight-until-next-command (beg end &optional buffer)
   (org-highlight beg end buffer)
   (add-hook 'pre-command-hook 'org-unhighlight-once))
@@ -15350,12 +16729,13 @@
                     (org-agenda-error)))
         (buffer (marker-buffer marker))
         (pos (marker-position marker))
+        (type (get-text-property (point) 'type))
         dbeg dend (n 0) conf)
     (org-with-remote-undo buffer
      (with-current-buffer buffer
        (save-excursion
         (goto-char pos)
-        (if (org-mode-p)
+        (if (and (org-mode-p) (not (member type '("sexp"))))
             (setq dbeg (progn (org-back-to-heading t) (point))
                   dend (org-end-of-subtree t))
           (setq dbeg (point-at-bol)
@@ -15502,6 +16882,16 @@
   "Marker pointing to the headline that last changed its TODO state
 by a remote command from the agenda.")
 
+(defun org-agenda-todo-nextset ()
+  "Switch TODO entry to next sequence."
+  (interactive)
+  (org-agenda-todo 'nextset))
+
+(defun org-agenda-todo-previousset ()
+  "Switch TODO entry to previous sequence."
+  (interactive)
+  (org-agenda-todo 'previousset))
+
 (defun org-agenda-todo (&optional arg)
   "Cycle TODO state of line at point, also in Org-mode file.
 This changes the line at point, all other lines in the agenda referring to
@@ -15673,10 +17063,12 @@
       (with-current-buffer buffer
        (widen)
        (goto-char pos)
-       (org-show-context 'agenda)
+       (save-excursion
+         (org-show-context 'agenda))
        (save-excursion
          (and (outline-next-heading)
               (org-flag-heading nil)))   ; show the next heading
+       (goto-char pos)
        (call-interactively 'org-set-tags)
        (end-of-line 1)
        (setq newhead (org-get-heading)))
@@ -15992,11 +17384,11 @@
 (defvar org-cdlatex-mode-map (make-sparse-keymap)
   "Keymap for the minor `org-cdlatex-mode'.")
 
-(define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
-(define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
-(define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
-(define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
-(define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
+(org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
+(org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
+(org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
+(org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
+(org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
 
 (defvar org-cdlatex-texmathp-advice-is-done nil
   "Flag remembering if we have applied the advice to texmathp already.")
@@ -16064,7 +17456,7 @@
        (while (string-match re str start)
          (cond
           ((= (match-end 0) (length str))
-           (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
+           (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
           ((= (match-end 0) (- (length str) 5))
            (throw 'exit nil))
           (t (setq start (match-end 0))))))
@@ -16156,11 +17548,12 @@
                      "Creating images for entry...%s"))))
        (message msg "")
        (narrow-to-region beg end)
+       (goto-char beg)
        (org-format-latex
         (concat "ltxpng/" (file-name-sans-extension
                            (file-name-nondirectory
                             buffer-file-name)))
-        default-directory 'overlays msg at)
+        default-directory 'overlays msg at 'forbuffer)
       (message msg "done.  Use `C-c C-c' to remove images.")))))
 
 (defvar org-latex-regexps
@@ -16173,7 +17566,7 @@
     ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
   "Regular expressions for matching embedded LaTeX.")
 
-(defun org-format-latex (prefix &optional dir overlays msg at)
+(defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
   "Replace LaTeX fragments with links to an image, and produce images."
   (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
   (let* ((prefixnodir (file-name-nondirectory prefix))
@@ -16210,7 +17603,7 @@
              (setq checkdir t)
              (or (file-directory-p todir) (make-directory todir)))
            (org-create-formula-image
-            txt movefile opt)
+            txt movefile opt forbuffer)
            (if overlays
                (progn
                  (setq ov (org-make-overlay beg end))
@@ -16229,31 +17622,27 @@
              (insert link))))))))
 
 ;; This function borrows from Ganesh Swami's latex2png.el
-(defun org-create-formula-image (string tofile options)
+(defun org-create-formula-image (string tofile options buffer)
   (let* ((tmpdir (if (featurep 'xemacs)
                     (temp-directory)
                   temporary-file-directory))
         (texfilebase (make-temp-name
                       (expand-file-name "orgtex" tmpdir)))
-
-;(texfilebase (make-temp-file "orgtex"))
-;       (dummy (delete-file texfilebase))
         (texfile (concat texfilebase ".tex"))
         (dvifile (concat texfilebase ".dvi"))
         (pngfile (concat texfilebase ".png"))
-        (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
-        (fg (or (plist-get options :foreground) "Black"))
-        (bg (or (plist-get options :background) "Transparent")))
+        (fnh (face-attribute 'default :height nil))
+        (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
+        (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
+        (fg (or (plist-get options (if buffer :foreground :html-foreground))
+                "Black"))
+        (bg (or (plist-get options (if buffer :background :html-background))
+                "Transparent")))
+    (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
+    (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
     (with-temp-file texfile
-      (insert "\\documentclass{article}
-\\usepackage{fullpage}
-\\usepackage{amssymb}
-\\usepackage[usenames]{color}
-\\usepackage{amsmath}
-\\usepackage{latexsym}
-\\usepackage[mathscr]{eucal}
-\\pagestyle{empty}
-\\begin{document}\n" string "\n\\end{document}\n"))
+      (insert org-format-latex-header
+             "\n\\begin{document}\n" string "\n\\end{document}\n"))
     (let ((dir default-directory))
       (condition-case nil
          (progn
@@ -16265,7 +17654,9 @@
        (progn (message "Failed to create dvi file from %s" texfile) nil)
       (call-process "dvipng" nil nil nil
                    "-E" "-fg" fg "-bg" bg
-                   "-x" scale "-y" scale "-T" "tight"
+                    "-D" dpi
+                   ;;"-x" scale "-y" scale
+                   "-T" "tight"
                    "-o" pngfile
                    dvifile)
       (if (not (file-exists-p pngfile))
@@ -16276,6 +17667,16 @@
              (delete-file (concat texfilebase e)))
        pngfile))))
 
+(defun org-dvipng-color (attr)
+  "Return an rgb color specification for dvipng."
+  (apply 'format "rgb %s %s %s"
+        (mapcar 'org-normalize-color
+                (color-values (face-attribute 'default attr nil)))))
+
+(defun org-normalize-color (value)
+  "Return string to be used as color value for an RGB component."
+  (format "%g" (/ value 65535.0)))
+
 ;;;; Exporting
 
 ;;; Variables, constants, and parameter plists
@@ -16300,16 +17701,19 @@
     (:headline-levels      . org-export-headline-levels)
     (:section-numbers      . org-export-with-section-numbers)
     (:table-of-contents    . org-export-with-toc)
+    (:preserve-breaks      . org-export-preserve-breaks)
     (:archived-trees       . org-export-with-archived-trees)
     (:emphasize            . org-export-with-emphasize)
     (:sub-superscript      . org-export-with-sub-superscripts)
     (:TeX-macros           . org-export-with-TeX-macros)
     (:LaTeX-fragments      . org-export-with-LaTeX-fragments)
+    (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
     (:fixed-width          . org-export-with-fixed-width)
     (:timestamps           . org-export-with-timestamps)
     (:tables               . org-export-with-tables)
     (:table-auto-headline  . org-export-highlight-first-table-line)
     (:style                . org-export-html-style)
+    (:agenda-style         . org-agenda-export-html-style) ;; FIXME: Does this 
work????
     (:convert-org-links    . org-export-html-link-org-files-as-html)
     (:inline-images        . org-export-html-inline-images)
     (:expand-quoted-html   . org-export-html-expand)
@@ -16359,7 +17763,8 @@
                    ("^"     . :sub-superscript)
                    ("*"     . :emphasize)
                    ("TeX"   . :TeX-macros)
-                   ("LaTeX" . :LaTeX-fragments)))
+                   ("LaTeX" . :LaTeX-fragments)
+                   ("skip"  . :skip-before-1st-heading)))
              o)
          (while (setq o (pop op))
            (if (string-match (concat (regexp-quote (car o))
@@ -16377,19 +17782,11 @@
                val)))
     dir))
 
-(defun org-export-find-first-heading-line (list)
-  "Remove all lines from LIST which are before the first headline."
-  (let ((orig-list list)
-       (re (concat "^" outline-regexp)))
-    (while (and list
-               (not (string-match re (car list))))
-      (pop list))
-    (or list orig-list)))
-
 (defun org-skip-comments (lines)
   "Skip lines starting with \"#\" and subtrees starting with COMMENT."
   (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
        (re2 "^\\(\\*+\\)[ \t\n\r]")
+       (case-fold-search nil)
        rtn line level)
     (while (setq line (pop lines))
       (cond
@@ -16420,6 +17817,7 @@
 
 \[a] export as ASCII
 \[h] export as HTML
+\[H] export as HTML to temporary buffer
 \[b] export as HTML and browse immediately
 \[x] export as XOXO
 
@@ -16437,6 +17835,8 @@
           (?a . org-export-as-ascii)
           (?h . org-export-as-html)
           (?b . org-export-as-html-and-open)
+          (?H . org-export-as-html-to-buffer)
+          (?R . org-export-region-as-html)
           (?x . org-export-as-xoxo)
           (?i . org-export-icalendar-this-file)
           (?I . org-export-icalendar-all-agenda-files)
@@ -16465,6 +17865,7 @@
     ("curren")
     ("yen")
     ("brvbar")
+    ("vert" . "&#124;")
     ("sect")
     ("uml")
     ("copy")
@@ -16766,26 +18167,44 @@
         (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
         (re-archive (concat ":" org-archive-tag ":"))
         (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
-        (htmlp (memq :for-html parameters))
+        (htmlp (plist-get parameters :for-html))
         (outline-regexp "\\*+")
-        rtn)
+        a b
+        rtn p)
     (save-excursion
       (set-buffer (get-buffer-create " org-mode-tmp"))
       (erase-buffer)
       (insert string)
+      ;; Remove license-to-kill stuff
+      (while (setq p (text-property-any (point-min) (point-max)
+                                       :org-license-to-kill t))
+       (delete-region p (next-single-property-change p :org-license-to-kill)))
+
       (let ((org-inhibit-startup t)) (org-mode))
       (untabify (point-min) (point-max))
 
+      ;; Get the correct stuff before the first headline
+      (when (plist-get parameters :skip-before-1st-heading)
+       (goto-char (point-min))
+       (when (re-search-forward "^\\*+[ \t]" nil t)
+         (delete-region (point-min) (match-beginning 0))
+         (goto-char (point-min))
+         (insert "\n")))
+      (when (plist-get parameters :add-text)
+       (goto-char (point-min))
+       (insert (plist-get parameters :add-text) "\n"))
+
       ;; Get rid of archived trees
       (when (not (eq org-export-with-archived-trees t))
        (goto-char (point-min))
        (while (re-search-forward re-archive nil t)
-         (if (not (org-on-heading-p))
+         (if (not (org-on-heading-p t))
              (org-end-of-subtree t)
            (beginning-of-line 1)
-           (delete-region
-            (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
-            (org-end-of-subtree t)))))
+           (setq a (if org-export-with-archived-trees
+                       (1+ (point-at-eol)) (point))
+                 b (org-end-of-subtree t))
+           (if (> b a) (delete-region a b)))))
 
       ;; Protect stuff from HTML processing
       (goto-char (point-min))
@@ -16801,7 +18220,7 @@
           '(org-protected t))))
       (goto-char (point-min))
       (while (re-search-forward
-             "^#\\+BEGIN_HTML\\>.*\\(\n.*\\)*?\n#\\+END_HTML\\>.*\n?" nil t)
+             "^#\\+BEGIN_HTML\\>.*\\(\\(\n.*\\)*?\n\\)#\\+END_HTML\\>.*\n?" 
nil t)
        (if htmlp
            (add-text-properties (match-beginning 1) (1+ (match-end 1))
                                 '(org-protected t))
@@ -16839,7 +18258,7 @@
         (goto-char (match-beginning 0))))
 
       ;; Convert LaTeX fragments to images
-      (when (memq :LaTeX-fragments parameters)
+      (when (plist-get parameters :LaTeX-fragments)
        (org-format-latex
         (concat "ltxpng/" (file-name-sans-extension
                            (file-name-nondirectory
@@ -16851,6 +18270,7 @@
       ;; Expand link abbreviations
       (goto-char (point-min))
       (while (re-search-forward re-plain-link nil t)
+       (goto-char (1- (match-end 0)))
        (org-if-unprotected
         (replace-match
          (concat
@@ -16858,6 +18278,7 @@
          t t)))
       (goto-char (point-min))
       (while (re-search-forward re-angle-link nil t)
+       (goto-char (1- (match-end 0)))
        (org-if-unprotected
         (replace-match
          (concat
@@ -16877,17 +18298,35 @@
          t t)))
 
       ;; Find multiline emphasis and put them into single line
-      (when (memq :emph-multiline parameters)
+      (when (plist-get  parameters :emph-multiline)
        (goto-char (point-min))
        (while (re-search-forward org-emph-re nil t)
+         (if (not (= (char-after (match-beginning 3))
+                     (char-after (match-beginning 4))))
          (org-if-unprotected
-          (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\  t)
-          (goto-char (1- (match-end 0))))))
+              (subst-char-in-region (match-beginning 0) (match-end 0)
+                                    ?\n ?\  t)
+              (goto-char (1- (match-end 0))))
+           (goto-char (1+ (match-beginning 0))))))
 
       (setq rtn (buffer-string)))
     (kill-buffer " org-mode-tmp")
     rtn))
 
+(defun org-export-grab-title-from-buffer ()
+  "Get a title for the current document, from looking at the buffer."
+  (let (buffer-read-only)
+    (save-excursion
+      (goto-char (point-min))
+      (let ((end (save-excursion (outline-next-heading) (point))))
+       (when (re-search-forward "^[ \t]*[^# \t\r\n].*\n" end t)
+         ;; Mark the line so that it will not be exported as normal text.
+         (org-unmodified
+          (add-text-properties (match-beginning 0) (match-end 0)
+                               (list :org-license-to-kill t)))
+         ;; Return the title string
+         (org-trim (match-string 0)))))))
+
 (defun org-solidify-link-text (s &optional alist)
   "Take link text and make a safe target out of it."
   (save-match-data
@@ -16959,16 +18398,7 @@
   (setq-default org-todo-line-regexp org-todo-line-regexp)
   (let* ((opt-plist (org-combine-plists (org-default-export-plist)
                                        (org-infile-export-plist)))
-        (region
-         (buffer-substring
-          (if (org-region-active-p) (region-beginning) (point-min))
-          (if (org-region-active-p) (region-end) (point-max))))
         (custom-times org-display-custom-times)
-        (lines (org-export-find-first-heading-line
-                (org-skip-comments
-                 (org-split-string
-                  (org-cleaned-string-for-export region)
-                  "[\r\n]"))))
         (org-ascii-current-indentation '(0 . 0))
         (level 0) line txt
         (umax nil)
@@ -16986,15 +18416,36 @@
         (time  (format-time-string "%X" (org-current-time)))
         (author      (plist-get opt-plist :author))
         (title       (or (plist-get opt-plist :title)
+                         (and (not
+                               (plist-get opt-plist :skip-before-1st-heading))
+                              (org-export-grab-title-from-buffer))
                          (file-name-sans-extension
                           (file-name-nondirectory buffer-file-name))))
         (email       (plist-get opt-plist :email))
         (language    (plist-get opt-plist :language))
         (quote-re0   (concat "^[ \t]*" org-quote-string "\\>"))
 ;       (quote-re    (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
-        (text        nil)
         (todo nil)
-        (lang-words nil))
+        (lang-words nil)
+        (region
+         (buffer-substring
+          (if (org-region-active-p) (region-beginning) (point-min))
+          (if (org-region-active-p) (region-end) (point-max))))
+        (lines (org-skip-comments
+                (org-split-string
+                 (org-cleaned-string-for-export
+                  region
+                  :skip-before-1st-heading
+                  (plist-get opt-plist :skip-before-1st-heading)
+                  :add-text (plist-get opt-plist :text))
+                 "[\r\n]")))
+        thetoc have-headings first-heading-pos
+        table-open table-buffer)
+
+    (let (buffer-read-only)
+      (org-unmodified
+       (remove-text-properties (point-min) (point-max)
+                              '(:org-license-to-kill t))))
 
     (setq org-last-level 1)
     (org-init-section-numbers)
@@ -17028,27 +18479,27 @@
                        "\n")))
     (if (and date time)
        (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
-    (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
 
     (insert "\n\n")
 
     (if org-export-with-toc
        (progn
-         (insert (nth 3 lang-words) "\n"
-                 (make-string (length (nth 3 lang-words)) ?=) "\n")
+         (push (concat (nth 3 lang-words) "\n") thetoc)
+         (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") 
thetoc)
          (mapcar '(lambda (line)
                     (if (string-match org-todo-line-regexp
                                       line)
                         ;; This is a headline
                         (progn
+                          (setq have-headings t)
                           (setq level (- (match-end 1) (match-beginning 1))
                                 level (org-tr-level level)
                                 txt (match-string 3 line)
                                 todo
                                 (or (and org-export-mark-todo-in-toc
                                          (match-beginning 2)
-                                         (not (equal (match-string 2 line)
-                                                     org-done-string)))
+                                         (not (member (match-string 2 line)
+                                                      org-done-keywords)))
                                        ; TODO, not DONE
                                     (and org-export-mark-todo-in-toc
                                          (= level umax-toc)
@@ -17067,12 +18518,15 @@
                                                 " " txt)))
                           (if (<= level umax-toc)
                               (progn
-                                (insert
+                                (push
+                                 (concat
                                  (make-string (* (1- level) 4) ?\ )
                                  (format (if todo "%s (*)\n" "%s\n") txt))
+                                 thetoc)
                                 (setq org-last-level level))
                             ))))
-                 lines)))
+                 lines)
+         (setq thetoc (if have-headings (nreverse thetoc) nil))))
 
     (org-init-section-numbers)
     (while (setq line (pop lines))
@@ -17091,12 +18545,44 @@
       (cond
        ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
        ;; a Headline
+       (setq first-heading-pos (or first-heading-pos (point)))
        (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
              txt (match-string 2 line))
        (org-ascii-level-start level txt umax lines))
+
+       ((and org-export-with-tables
+            (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
+       (if (not table-open)
+           ;; New table starts
+           (setq table-open t table-buffer nil))
+       ;; Accumulate lines
+       (setq table-buffer (cons line table-buffer))
+       (when (or (not lines)
+                 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
+                                    (car lines))))
+         (setq table-open nil
+               table-buffer (nreverse table-buffer))
+         (insert (mapconcat
+                  (lambda (x)
+                    (org-fix-indentation x org-ascii-current-indentation))
+                  (org-format-table-ascii table-buffer)
+                  "\n") "\n")))
        (t
        (insert (org-fix-indentation line org-ascii-current-indentation) 
"\n"))))
     (normal-mode)
+
+    ;; insert the table of contents
+    (when thetoc
+      (goto-char (point-min))
+      (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
+         (progn
+           (goto-char (match-beginning 0))
+           (replace-match ""))
+       (goto-char first-heading-pos))
+      (mapc 'insert thetoc)
+      (or (looking-at "[ \t]*\n[ \t]*\n")
+         (insert "\n\n")))
+
     (save-buffer)
     ;; remove display and invisible chars
     (let (beg end)
@@ -17124,8 +18610,8 @@
            (progn
              (setq lv (- (match-end 1) (match-beginning 1))
                    todo (and (match-beginning 2)
-                             (not (equal (match-string 2 line)
-                                         org-done-string))))
+                             (not (member (match-string 2 line)
+                                         org-done-keywords))))
                                        ; TODO, not DONE
              (if (<= lv level) (throw 'exit nil))
              (if todo (throw 'exit t))))))))
@@ -17187,7 +18673,7 @@
 command."
   (interactive
    (list (progn
-          (message "Export visible: [a]SCII  [h]tml  [b]rowse HTML  [x]OXO  [ 
]keep buffer")
+          (message "Export visible: [a]SCII  [h]tml  [b]rowse HTML [H/R]uffer 
with HTML  [x]OXO  [ ]keep buffer")
           (read-char-exclusive))
         current-prefix-arg))
   (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
@@ -17198,6 +18684,8 @@
                                (?b . org-export-as-html-and-open)
                                (?\C-b . org-export-as-html-and-open)
                                (?h . org-export-as-html)
+                               (?H . org-export-as-html-to-buffer)
+                               (?R . org-export-region-as-html)
                                (?x . org-export-as-xoxo)))))
         (keepp (equal type ?\ ))
         (file buffer-file-name)
@@ -17253,10 +18741,11 @@
 #+EMAIL:     %s
 #+LANGUAGE:  %s
 #+TEXT:      Some descriptive text to be emitted.  Several lines OK.
-#+OPTIONS:   H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
+#+OPTIONS:   H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s 
LaTeX:%s skip:%s
 #+CATEGORY:  %s
 #+SEQ_TODO:  %s
 #+TYP_TODO:  %s
+#+PRIORITIES: %c %c %c
 #+STARTUP:   %s %s %s %s %s
 #+TAGS:      %s
 #+ARCHIVE:   %s
@@ -17274,13 +18763,11 @@
    org-export-with-emphasize
    org-export-with-TeX-macros
    org-export-with-LaTeX-fragments
+   org-export-skip-text-before-1st-heading
    (file-name-nondirectory buffer-file-name)
-   (if (equal org-todo-interpretation 'sequence)
-       (mapconcat 'identity org-todo-keywords " ")
-     "TODO FEEDBACK VERIFY DONE")
-   (if (equal org-todo-interpretation 'type)
-       (mapconcat 'identity org-todo-keywords " ")
-     "Me Jason Marie DONE")
+   "TODO FEEDBACK VERIFY DONE"
+   "Me Jason Marie DONE"
+   org-highest-priority org-lowest-priority org-default-priority
    (cdr (assoc org-startup-folded
               '((nil . "showall") (t . "overview") (content . "content"))))
    (if org-odd-levels-only "odd" "oddeven")
@@ -17372,19 +18859,96 @@
        --visit=MyFile --funcall org-export-as-html-batch"
   (org-export-as-html org-export-headline-levels 'hidden))
 
-(defun org-export-as-html (arg &optional hidden ext-plist)
+(defun org-export-as-html-to-buffer (arg)
+  "Call `org-exort-as-html` with output to a temporary buffer.
+No file is created.  The prefix ARG is passed through to `org-export-as-html'."
+  (interactive "P")
+  (org-export-as-html arg nil nil "*Org HTML Export*")
+  (switch-to-buffer-other-window "*Org HTML Export*"))
+
+(defun org-replace-region-by-html (beg end)
+  "Assume the current region has org-mode syntax, and convert it to HTML.
+This can be used in any buffer.  For example, you could write an
+itemized list in org-mode syntax in an HTML buffer and then use this
+command to convert it."
+  (interactive "r")
+  (let (reg html buf)
+    (if (org-mode-p)
+       (setq html (org-export-region-as-html
+                   beg end t 'string))
+      (setq reg (buffer-substring beg end)
+           buf (get-buffer-create "*Org tmp*"))
+      (save-excursion
+       (set-buffer buf)
+       (erase-buffer)
+       (insert reg)
+       (org-mode)
+       (setq html (org-export-region-as-html
+                   (point-min) (point-max) t 'string)))
+      (kill-buffer buf))
+    (delete-region beg end)
+    (insert html)))
+
+(defun org-export-region-as-html (beg end &optional body-only buffer)
+  "Convert region from BEG to END in org-mode buffer to HTML.
+If prefix arg BODY-ONLY is set, omit file header, footer, and table of
+contents, and only produce the region of converted text, useful for
+cut-and-paste operations.
+If BUFFER is a buffer or a string, use/create that buffer as a target
+of the converted HTML.  If BUFFER is the symbol `string', return the
+produced HTML as a string and leave not buffer behind.  For example,
+a Lisp program could call this function in the following way:
+
+  (setq html (org-export-region-as-html beg end t 'string))
+
+When called interactively, the output buffer is selected, and shown
+in a window.  A non-interactive call will only retunr the buffer."
+  (interactive "r\nP")
+  (when (interactive-p)
+    (setq buffer "*Org HTML EXPORT*"))
+  (let ((transient-mark-mode t) (zmacs-regions t)
+       rtn)
+    (goto-char end)
+    (set-mark (point)) ;; to activate the region
+    (goto-char beg)
+    (setq rtn (org-export-as-html
+              nil nil nil
+              buffer body-only))
+    (if (fboundp 'deactivate-mark) (deactivate-mark))
+    (if (and (interactive-p) (bufferp rtn))
+       (switch-to-buffer-other-window rtn)
+      rtn)))
+
+(defun org-export-as-html (arg &optional hidden ext-plist
+                              to-buffer body-only)
   "Export the outline as a pretty HTML file.
-If there is an active region, export only the region.
-The prefix ARG specifies how many levels of the outline should become
-headlines.  The default is 3.  Lower levels will become bulleted lists.
-When HIDDEN is non-nil, don't display the HTML buffer.
+If there is an active region, export only the region.  The prefix
+ARG specifies how many levels of the outline should become
+headlines.  The default is 3.  Lower levels will become bulleted
+lists.  When HIDDEN is non-nil, don't display the HTML buffer.
 EXT-PLIST is a property list with external parameters overriding
-org-mode's default settings, but still inferior to file-local settings."
+org-mode's default settings, but still inferior to file-local
+settings.  When TO-BUFFER is non-nil, create a buffer with that
+name and export to that buffer.  If TO-BUFFER is the symbol `string',
+don't leave any buffer behind but just return the resulting HTML as
+a string.  When BODY-ONLY is set, don't produce the file header and footer,
+simply return the content of <body>...</body>, without even
+the body tags themselves."
   (interactive "P")
+
+  ;; Make sure we have a file name when we need it.
+  (when (and (not (or to-buffer body-only))
+            (not buffer-file-name))
+    (if (buffer-base-buffer)
+       (org-set-local 'buffer-file-name
+                      (with-current-buffer (buffer-base-buffer)
+                        buffer-file-name))
+      (error "Need a file name to be able to export.")))
+
   (message "Exporting...")
   (setq-default org-todo-line-regexp org-todo-line-regexp)
   (setq-default org-deadline-line-regexp org-deadline-line-regexp)
-  (setq-default org-done-string org-done-string)
+  (setq-default org-done-keywords org-done-keywords)
   (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
   (let* ((opt-plist (org-combine-plists (org-default-export-plist)
                                        ext-plist
@@ -17392,42 +18956,42 @@
 
         (style (plist-get opt-plist :style))
         (link-validate (plist-get opt-plist :link-validation-function))
-        valid
+        valid thetoc have-headings first-heading-pos
         (odd org-odd-levels-only)
         (region-p (org-region-active-p))
-         (region
-          (buffer-substring
-           (if region-p (region-beginning) (point-min))
-           (if region-p (region-end) (point-max))))
         ;; The following two are dynamically scoped into other
         ;; routines below.
         (org-current-export-dir (org-export-directory :html opt-plist))
         (org-current-export-file buffer-file-name)
-         (all_lines
-          (org-skip-comments (org-split-string
-                             (org-cleaned-string-for-export
-                              region :emph-multiline :for-html
-                              (if (plist-get opt-plist :LaTeX-fragments)
-                                  :LaTeX-fragments))
-                             "[\r\n]")))
-         (lines (org-export-find-first-heading-line all_lines))
          (level 0) (line "") (origline "") txt todo
          (umax nil)
          (umax-toc nil)
-         (filename (concat (file-name-as-directory
+         (filename (if to-buffer nil
+                    (concat (file-name-as-directory
                            (org-export-directory :html opt-plist))
                           (file-name-sans-extension
                            (file-name-nondirectory buffer-file-name))
-                          ".html"))
-        (current-dir (file-name-directory buffer-file-name))
-         (buffer (find-file-noselect filename))
+                            ".html")))
+        (current-dir (if buffer-file-name
+                         (file-name-directory buffer-file-name)
+                       default-directory))
+        (buffer (if to-buffer
+                    (cond
+                     ((eq to-buffer 'string) (get-buffer-create "*Org HTML 
Export*"))
+                     (t (get-buffer-create  to-buffer)))
+                  (find-file-noselect filename)))
          (org-levels-open (make-vector org-level-max nil))
         (date (format-time-string "%Y/%m/%d" (current-time)))
         (time  (format-time-string "%X" (org-current-time)))
          (author      (plist-get opt-plist :author))
         (title       (or (plist-get opt-plist :title)
+                         (and (not
+                               (plist-get opt-plist :skip-before-1st-heading))
+                              (org-export-grab-title-from-buffer))
+                         (and buffer-file-name
                          (file-name-sans-extension
-                          (file-name-nondirectory buffer-file-name))))
+                               (file-name-nondirectory buffer-file-name)))
+                         "UNTITLED"))
         (quote-re0   (concat "^[ \t]*" org-quote-string "\\>"))
         (quote-re    (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
         (inquote     nil)
@@ -17438,7 +19002,6 @@
         (llt org-plain-list-ordered-item-terminator)
         (email       (plist-get opt-plist :email))
          (language    (plist-get opt-plist :language))
-        (text        (plist-get opt-plist :text))
         (lang-words  nil)
         (target-alist nil) tg
         (head-count  0) cnt
@@ -17450,11 +19013,34 @@
         (charset (and coding-system
                       (fboundp 'coding-system-get)
                       (coding-system-get coding-system 'mime-charset)))
+         (region
+          (buffer-substring
+           (if region-p (region-beginning) (point-min))
+           (if region-p (region-end) (point-max))))
+         (lines
+          (org-skip-comments (org-split-string
+                             (org-cleaned-string-for-export
+                              region
+                              :emph-multiline t
+                              :for-html t
+                              :skip-before-1st-heading
+                              (plist-get opt-plist :skip-before-1st-heading)
+                              :add-text
+                              (plist-get opt-plist :text)
+                              :LaTeX-fragments
+                              (plist-get opt-plist :LaTeX-fragments))
+                             "[\r\n]")))
         table-open type
         table-buffer table-orig-buffer
-        ind start-is-num starter
+        ind start-is-num starter didclose
         rpl path desc descp desc1 desc2 link
         )
+
+    (let (buffer-read-only)
+      (org-unmodified
+       (remove-text-properties (point-min) (point-max)
+                              '(:org-license-to-kill t))))
+
     (message "Exporting...")
 
     (setq org-last-level 1)
@@ -17465,9 +19051,7 @@
                          (assoc "en" org-export-language-setup)))
 
     ;; Switch to the output buffer
-    (if (or hidden t)
         (set-buffer buffer)
-      (switch-to-buffer-other-window buffer))
     (erase-buffer)
     (fundamental-mode)
     (let ((case-fold-search nil)
@@ -17483,7 +19067,7 @@
       (setq umax-toc (if (integerp org-export-with-toc)
                         (min org-export-with-toc umax)
                       umax))
-
+      (unless body-only
       ;; File header
       (insert (format
                "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
@@ -17499,29 +19083,29 @@
 %s
 </head><body>
 "
-              language language (org-html-expand title) (or charset 
"iso-8859-1")
-              date time author style))
-
+                language language (org-html-expand title)
+                (or charset "iso-8859-1") date time author style))
 
       (insert (or (plist-get opt-plist :preamble) ""))
 
       (when (plist-get opt-plist :auto-preamble)
        (if title     (insert (format org-export-html-title-format
-                                     (org-html-expand title))))
-       (if text      (insert "<p>\n" (org-html-expand text) "</p>")))
+                                   (org-html-expand title))))))
 
-      (if org-export-with-toc
+      (if (and org-export-with-toc (not body-only))
          (progn
-           (insert (format "<h%d>%s</h%d>\n"
+           (push (format "<h%d>%s</h%d>\n"
                            org-export-html-toplevel-hlevel
                            (nth 3 lang-words)
-                           org-export-html-toplevel-hlevel))
-           (insert "<ul>\n<li>")
+                         org-export-html-toplevel-hlevel)
+                 thetoc)
+           (push "<ul>\n<li>" thetoc)
            (setq lines
            (mapcar '(lambda (line)
                       (if (string-match org-todo-line-regexp line)
                           ;; This is a headline
                           (progn
+                         (setq have-headings t)
                             (setq level (- (match-end 1) (match-beginning 1))
                                   level (org-tr-level level)
                                   txt (save-match-data
@@ -17531,8 +19115,8 @@
                                   todo
                                   (or (and org-export-mark-todo-in-toc
                                            (match-beginning 2)
-                                           (not (equal (match-string 2 line)
-                                                       org-done-string)))
+                                        (not (member (match-string 2 line)
+                                                     org-done-keywords)))
                                        ; TODO, not DONE
                                       (and org-export-mark-todo-in-toc
                                            (= level umax-toc)
@@ -17546,21 +19130,22 @@
                             (if org-export-with-section-numbers
                                 (setq txt (concat (org-section-number level)
                                                   " " txt)))
+                         (if (<= level (max umax umax-toc))
+                             (setq head-count (+ head-count 1)))
                             (if (<= level umax-toc)
                                 (progn
-                                  (setq head-count (+ head-count 1))
                                   (if (> level org-last-level)
                                       (progn
                                         (setq cnt (- level org-last-level))
                                         (while (>= (setq cnt (1- cnt)) 0)
-                                          (insert "\n<ul>\n<li>"))
-                                        (insert "\n")))
+                                       (push "\n<ul>\n<li>" thetoc))
+                                     (push "\n" thetoc)))
                                   (if (< level org-last-level)
                                       (progn
                                         (setq cnt (- org-last-level level))
                                         (while (>= (setq cnt (1- cnt)) 0)
-                                          (insert "</li>\n</ul>"))
-                                        (insert "\n")))
+                                       (push "</li>\n</ul>" thetoc))
+                                     (push "\n" thetoc)))
                                   ;; Check for targets
                                   (while (string-match org-target-regexp line)
                                     (setq tg (match-string 1 line)
@@ -17572,12 +19157,12 @@
                                           target-alist))
                                   (while (string-match 
"&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
                                     (setq txt (replace-match "" t t txt)))
-                                  (insert
+                               (push
                                    (format
                                     (if todo
                                         "</li>\n<li><a href=\"#sec-%d\"><span 
class=\"todo\">%s</span></a>"
                                       "</li>\n<li><a href=\"#sec-%d\">%s</a>")
-                                    head-count txt))
+                                 head-count txt) thetoc)
 
                                   (setq org-last-level level))
                               )))
@@ -17585,8 +19170,9 @@
                    lines))
            (while (> org-last-level 0)
              (setq org-last-level (1- org-last-level))
-             (insert "</li>\n</ul>\n"))
-           ))
+             (push "</li>\n</ul>\n" thetoc))
+           (setq thetoc (if have-headings (nreverse thetoc) nil))))
+
       (setq head-count 0)
       (org-init-section-numbers)
 
@@ -17618,7 +19204,16 @@
 
          ;; Protected HTML
          (when (get-text-property 0 'org-protected line)
+           (let (par)
+             (when (re-search-backward
+                    "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
+               (setq par (match-string 1))
+               (replace-match "\\2\n"))
            (insert line "\n")
+             (while (and lines
+                         (get-text-property 0 'org-protected (car lines)))
+               (insert (pop lines) "\n"))
+             (and par (insert "<p>\n")))
            (throw 'nextline nil))
 
          ;; Horizontal line
@@ -17676,7 +19271,8 @@
              (setq rpl
                    (concat
                     "<a href=\"#"
-                    (org-solidify-link-text path target-alist)
+                    (org-solidify-link-text
+                     (save-match-data (org-link-unescape path)) target-alist)
                     "\">" desc "</a>")))
             ((member type '("http" "https")) ; FIXME: need to test this.
              ;; standard URL, just check if we need to inline an image
@@ -17738,12 +19334,24 @@
          ;; TODO items
          (if (and (string-match org-todo-line-regexp line)
                   (match-beginning 2))
-             (if (equal (match-string 2 line) org-done-string)
+             (if (member (match-string 2 line) org-done-keywords)
                  (setq line (replace-match
                              "<span class=\"done\">\\2</span>"
                              t nil line 2))
-               (setq line (replace-match "<span class=\"todo\">\\2</span>"
-                                         t nil line 2))))
+               (setq line
+                      (concat (substring line 0 (match-beginning 2))
+                              "<span class=\"todo\">" (match-string 2 line)
+                              "</span>" (substring line (match-end 2))))))
+
+         ;; Does this contain a reference to a footnote?
+         (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line)
+           (let ((n (match-string 2 line)))
+             (setq line
+                   (replace-match
+                    (format
+                     "%s<sup><a class=\"footref\" name=\"fnr.%s\" 
href=\"#fn.%s\">%s</a></sup>"
+                     (match-string 1 line) n n n)
+                    t t line))))
 
          (cond
           ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
@@ -17752,7 +19360,8 @@
                  txt (match-string 2 line))
            (if (string-match quote-re0 txt)
                (setq txt (replace-match "" t t txt)))
-           (if (<= level umax) (setq head-count (+ head-count 1)))
+           (if (<= level (max umax umax-toc))
+               (setq head-count (+ head-count 1)))
            (when in-local-list
              ;; Close any local lists before inserting a new header line
              (while local-list-num
@@ -17761,6 +19370,7 @@
                (pop local-list-num))
              (setq local-list-indent nil
                    in-local-list nil))
+           (setq first-heading-pos (or first-heading-pos (point)))
            (org-html-level-start level txt umax
                                  (and org-export-with-toc (<= level umax))
                                  head-count)
@@ -17801,11 +19411,15 @@
                    line (substring line (match-beginning 5)))
              (unless (string-match "[^ \t]" line)
                ;; empty line.  Pretend indentation is large.
-               (setq ind (1+ (or (car local-list-indent) 1))))
+               (setq ind (if org-empty-line-terminates-plain-lists
+                             0
+                           (1+ (or (car local-list-indent) 1)))))
+             (setq didclose nil)
              (while (and in-local-list
                          (or (and (= ind (car local-list-indent))
                                   (not starter))
                              (< ind (car local-list-indent))))
+               (setq didclose t)
                (org-close-li)
                (insert (if (car local-list-num) "</ol>\n" "</ul>"))
                (pop local-list-num) (pop local-list-indent)
@@ -17814,7 +19428,7 @@
               ((and starter
                     (or (not in-local-list)
                         (> ind (car local-list-indent))))
-               ;; Start new (level of ) list
+               ;; Start new (level of) list
                (org-close-par-maybe)
                (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
                (push start-is-num local-list-num)
@@ -17823,7 +19437,10 @@
               (starter
                ;; continue current list
                (org-close-li)
-               (insert "<li>\n")))
+               (insert "<li>\n"))
+              (didclose
+               ;; we did close a list, normal text follows: need <p>
+               (org-open-par)))
              (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
                  (setq line
                        (replace-match
@@ -17837,6 +19454,13 @@
            ;; also start a new paragraph.
            (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
 
+           ;; Is this the start of a footnote?
+           (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
+             (org-close-par-maybe)
+             (let ((n (match-string 1 line)))
+               (setq line (replace-match
+                           (format "<p class=\"footnote\"><sup><a 
class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t 
line))))
+
            ;; Check if the line break needs to be conserved
            (cond
             ((string-match "\\\\\\\\[ \t]*$" line)
@@ -17860,6 +19484,7 @@
                            (and org-export-with-toc (<= level umax))
                            head-count)
 
+      (unless body-only
       (when (plist-get opt-plist :auto-postamble)
        (when author
          (insert "<p class=\"author\"> "
@@ -17876,8 +19501,26 @@
       (if org-export-html-with-timestamp
          (insert org-export-html-html-helper-timestamp))
       (insert (or (plist-get opt-plist :postamble) ""))
-      (insert "</body>\n</html>\n")
+       (insert "</body>\n</html>\n"))
+
       (normal-mode)
+      (if (eq major-mode default-major-mode) (html-mode))
+
+      ;; insert the table of contents
+      (goto-char (point-min))
+      (when thetoc
+       (if (or (re-search-forward
+                "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
+               (re-search-forward
+                "\\[TABLE-OF-CONTENTS\\]" nil t))
+           (progn
+             (goto-char (match-beginning 0))
+             (replace-match ""))
+         (goto-char first-heading-pos)
+         (when (looking-at "\\s-*</p>")
+           (goto-char (match-end 0))
+           (insert "\n")))
+       (mapc 'insert thetoc))
       ;; remove empty paragraphs and lists
       (goto-char (point-min))
       (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
@@ -17885,13 +19528,62 @@
       (goto-char (point-min))
       (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
        (replace-match ""))
-      (save-buffer)
+      (or to-buffer (save-buffer))
       (goto-char (point-min))
-      (message "Exporting... done"))))
+      (message "Exporting... done")
+      (if (eq to-buffer 'string)
+         (prog1 (buffer-substring (point-min) (point-max))
+           (kill-buffer (current-buffer)))
+       (current-buffer)))))
+
+(defvar org-table-colgroup-info nil) ;; FIXME: mode to a better place
+(defun org-format-table-ascii (lines)
+  "Format a table for ascii export."
+  (if (stringp lines)
+      (setq lines (org-split-string lines "\n")))
+  (if (not (string-match "^[ \t]*|" (car lines)))
+      ;; Table made by table.el - test for spanning
+      lines
+
+    ;; A normal org table
+    ;; Get rid of hlines at beginning and end
+    (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
+    (setq lines (nreverse lines))
+    (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
+    (setq lines (nreverse lines))
+    (when org-export-table-remove-special-lines
+      ;; Check if the table has a marking column.  If yes remove the
+      ;; column and the special lines
+      (setq lines (org-table-clean-before-export lines)))
+    ;; Get rid of the vertical lines except for grouping
+    (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
+         rtn line vl1 start)
+      (while (setq line (pop lines))
+       (if (string-match org-table-hline-regexp line)
+           (and (string-match "|\\(.*\\)|" line)
+                (setq line (replace-match " \\1" t nil line)))
+         (setq start 0 vl1 vl)
+         (while (string-match "|" line start)
+           (setq start (match-end 0))
+           (or (pop vl1) (setq line (replace-match " " t t line)))))
+       (push line rtn))
+      (nreverse rtn))))
+
+(defun org-colgroup-info-to-vline-list (info)
+  (let (vl new last rtn line)
+    (while info
+      (setq last new new (pop info))
+      (if (or (memq last '(:end :startend))
+             (memq new  '(:start :startend)))
+         (push t vl)
+       (push nil vl)))
+    (setq vl (cons nil (nreverse vl)))))
 
 
 (defun org-format-table-html (lines olines)
   "Find out which HTML converter to use and return the HTML code."
+  (if (stringp lines)
+      (setq lines (org-split-string lines "\n")))
   (if (string-match "^[ \t]*|" (car lines))
       ;; A normal org table
       (org-format-org-table-html lines)
@@ -17931,7 +19623,7 @@
                              (lambda (x) (string-match "^[ \t]*|-" x))
                              (cdr lines)))))
        (nlines 0) fnum i
-       tbopen line fields html)
+       tbopen line fields html gr)
     (if splice (setq head nil))
     (unless splice (push (if head "<thead>" "<tbody>") html))
     (setq tbopen t)
@@ -17957,8 +19649,10 @@
                                  (string-match org-table-number-regexp x))
                             (incf (aref fnum i)))
                         (if head
-                            (concat "<th>" x "</th>")
-                          (concat "<td>" x "</td>")))
+                            (concat (car org-export-table-header-tags) x
+                                    (cdr org-export-table-header-tags))
+                          (concat (car org-export-table-data-tags) x
+                                  (cdr org-export-table-data-tags))))
                       fields "")
                      "</tr>")
              html)))
@@ -17969,9 +19663,12 @@
       ;; Put in COL tags with the alignment (unfortuntely often ignored...)
       (push (mapconcat
             (lambda (x)
-              (format "<COL align=\"%s\">"
+              (setq gr (pop org-table-colgroup-info))
+              (format "%s<COL align=\"%s\">%s"
+                      (if (memq gr '(:start :startend)) "<colgroup>" "")
                       (if (> (/ (float x) nlines) org-table-number-fraction)
-                          "right" "left")))
+                          "right" "left")
+                      (if (memq gr '(:end :startend)) "</colgroup>" "")))
             fnum "")
            html)
       (push org-export-html-table-tag html))
@@ -17980,34 +19677,52 @@
 (defun org-table-clean-before-export (lines)
   "Check if the table has a marking column.
 If yes remove the column and the special lines."
+  (setq org-table-colgroup-info nil)
   (if (memq nil
            (mapcar
             (lambda (x) (or (string-match "^[ \t]*|-" x)
                             (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
             lines))
       (progn
-       (setq org-table-clean-did-remove-column-1 nil)
-       lines)
-    (setq org-table-clean-did-remove-column-1 t)
+       (setq org-table-clean-did-remove-column nil)
+       (delq nil
+             (mapcar
+              (lambda (x)
+                (cond
+                 ((string-match  "^[ \t]*| */ *|" x)
+                  (setq org-table-colgroup-info
+                        (mapcar (lambda (x)
+                                  (cond ((member x '("<" "&lt;")) :start)
+                                        ((member x '(">" "&gt;")) :end)
+                                        ((member x '("<>" "&lt;&gt;")) 
:startend)
+                                        (t nil)))
+                                (org-split-string x "[ \t]*|[ \t]*")))
+                  nil)
+                 (t x)))
+              lines)))
+    (setq org-table-clean-did-remove-column t)
     (delq nil
          (mapcar
-          (lambda (x) (if (string-match "^[ \t]*| *[!_^/] *|" x)
-                          nil ; ignore this line
-                        (and (or (string-match "^[ \t]*|-+\\+" x)
-                                 (string-match "^[ \t]*|[^|]*|" x))
-                             (replace-match "|" t t x))))
+          (lambda (x)
+            (cond
+             ((string-match  "^[ \t]*| */ *|" x)
+              (setq org-table-colgroup-info
+                    (mapcar (lambda (x)
+                              (cond ((member x '("<" "&lt;")) :start)
+                                    ((member x '(">" "&gt;")) :end)
+                                    ((member x '("<>" "&lt;&gt;")) :startend)
+                                    (t nil)))
+                            (cdr (org-split-string x "[ \t]*|[ \t]*"))))
+              nil)
+             ((string-match "^[ \t]*| *[!_^/] *|" x)
+              nil) ; ignore this line
+             ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
+                  (string-match "^\\([ \t]*\\)|[^|]*|" x))
+              ;; remove the first column
+              (replace-match "\\1|" t nil x))
+             (t (error "This should not happen"))))
           lines))))
 
-(defun org-fake-empty-table-line (line)
-  "Replace everything except \"|\" with spaces."
-  (let ((i (length line))
-       (newstr (copy-sequence line)))
-    (while (> i 0)
-      (setq i (1- i))
-      (if (not (eq (aref newstr i) ?|))
-         (aset newstr i ?\ )))
-    newstr))
-
 (defun org-format-table-table-html (lines)
   "Format a table generated by table.el into HTML.
 This conversion does *not* use `table-generate-source' from table.el.
@@ -18024,15 +19739,19 @@
            (progn
              (if field-buffer
                  (progn
-                   (setq html (concat
+                   (setq
+                    html
+                    (concat
                                html
                                "<tr>"
                                (mapconcat
                                 (lambda (x)
                                   (if (equal x "") (setq x empty))
                                   (if head
-                                      (concat "<th>" x "</th>\n")
-                                    (concat "<td>" x "</td>\n")))
+                            (concat (car org-export-table-header-tags) x
+                                    (cdr org-export-table-header-tags))
+                          (concat (car org-export-table-data-tags) x
+                                  (cdr org-export-table-data-tags))))
                                 field-buffer "\n")
                                "</tr>\n"))
                    (setq head nil)
@@ -18115,6 +19834,9 @@
   (when org-export-remove-timestamps-from-toc
     (while (string-match org-maybe-keyword-time-regexp s)
       (setq s (replace-match "" t t s))))
+  (while (string-match org-bracket-link-regexp s)
+    (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
+                          t t s)))
   s)
 
 (defun org-html-expand (string)
@@ -18179,27 +19901,42 @@
    "\\(\\(?:\\*\\|address@hidden \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
   "The regular expression matching a sub- or superscript.")
 
+;(let ((s "a\\_b"))
+;  (and (string-match org-match-substring-regexp s)
+;       (conca      t (match-string 1 s) ":::" (match-string 2 s))))
+
 (defun org-export-html-convert-sub-super (string)
   "Convert sub- and superscripts in STRING to HTML."
-  (let (key c)
-    (while (string-match org-match-substring-regexp string)
-      (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
-      (setq c (or (match-string 8 string)
+  (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
+    (while (string-match org-match-substring-regexp string s)
+      (if (and requireb (match-end 8))
+         (setq s (match-end 2))
+       (setq s (match-end 1)
+             key (if (string= (match-string 2 string) "_") "sub" "sup")
+             c (or (match-string 8 string)
                  (match-string 6 string)
-                 (match-string 5 string)))
-      (setq string (replace-match
+                   (match-string 5 string))
+             string (replace-match
                    (concat (match-string 1 string)
                            "<" key ">" c "</" key ">")
-                   t t string)))
+                     t t string))))
     (while (string-match "\\\\\\([_^]\\)" string)
-      (setq string (replace-match (match-string 1 string) t t string))))
-  string)
+      (setq string (replace-match (match-string 1 string) t t string)))
+    string))
 
 (defun org-export-html-convert-emphasize (string)
   "Apply emphasis."
-  (while (string-match org-emph-re string)
-    (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)))
-  string)
+  (let ((s 0))
+    (while (string-match org-emph-re string s)
+      (if (not (equal
+               (substring string (match-beginning 3) (1+ (match-beginning 3)))
+               (substring string (match-beginning 4) (1+ (match-beginning 
4)))))
+         (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))
+       (setq s (1+ s))))
+    string))
 
 (defvar org-par-open nil)
 (defun org-open-par ()
@@ -18216,10 +19953,6 @@
   "Close <li> if necessary."
   (org-close-par-maybe)
   (insert "</li>\n"))
-;  (when (save-excursion
-;        (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
-;    (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
-;      (insert "</li>"))))
 
 (defun org-html-level-start (level title umax with-toc head-count)
   "Insert a new level in HTML export.
@@ -18260,7 +19993,7 @@
            (setq title (concat (org-section-number level) " " title)))
        (setq level (+ level org-export-html-toplevel-hlevel -1))
        (if with-toc
-           (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
+           (insert (format "\n<h%d id=\"sec-%d\">%s</h%d>\n"
                            level head-count title level))
          (insert (format "\n<h%d>%s</h%d>\n" level title level)))
        (org-open-par)))))
@@ -18268,7 +20001,7 @@
 (defun org-html-level-close (&rest args)
   "Terminate one level in HTML export."
   (org-close-li)
-  (insert "</ul>"))
+  (insert "</ul>\n"))
 
 ;;; iCalendar export
 
@@ -18300,11 +20033,13 @@
 If COMBINE is non-nil, combine all calendar entries into a single large
 file and store it under the name `org-combined-agenda-icalendar-file'."
   (save-excursion
+    (org-prepare-agenda-buffers files)
     (let* ((dir (org-export-directory
                 :ical (list :publishing-directory
                             org-export-publishing-directory)))
           file ical-file ical-buffer category started org-agenda-new-buffers)
 
+      (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
       (when combine
        (setq ical-file
              (if (file-name-absolute-p org-combined-agenda-icalendar-file)
@@ -18349,16 +20084,20 @@
 (defun org-print-icalendar-entries (&optional combine)
   "Print iCalendar entries for the current Org-mode file to `standard-output'.
 When COMBINE is non nil, add the category to each line."
-  (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
+  (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
+       (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
        (org-category-table (org-get-category-table))
        (dts (org-ical-ts-to-string
              (format-time-string (cdr org-time-stamp-formats) (current-time))
              "DTSTART"))
-       hd ts ts2 state status (inc t) pos
-       scheduledp deadlinep tmp pri category)
+       hd ts ts2 state status (inc t) pos b sexp rrule
+       scheduledp deadlinep tmp pri category
+       (sexp-buffer (get-buffer-create "*ical-tmp*")))
     (save-excursion
       (goto-char (point-min))
-      (while (re-search-forward org-ts-regexp nil t)
+      (while (re-search-forward re1 nil t)
+       (catch :skip
+         (org-agenda-skip)
        (setq pos (match-beginning 0)
              ts (match-string 0)
              inc t
@@ -18379,38 +20118,76 @@
        (if (or (string-match org-tr-regexp hd)
                (string-match org-ts-regexp hd))
            (setq hd (replace-match "" t t hd)))
+         (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
+             (setq rrule
+                   (concat "\nRRULE:FREQ="
+                           (cdr (assoc
+                                 (match-string 2 ts)
+                                 '(("d" . "DAILY")("w" . "WEEKLY")
+                                   ("m" . "MONTHLY")("y" . "YEARLY"))))
+                           ";INTERVAL=" (match-string 1 ts)))
+           (setq rrule ""))
        (if (string-match org-bracket-link-regexp hd)
            (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
                                      (match-string 1 hd))
                                    t t hd)))
        (if deadlinep (setq hd (concat "DL: " hd)))
        (if scheduledp (setq hd (concat "S: " hd)))
+         (if (string-match "\\`<%%" ts)
+             (with-current-buffer sexp-buffer
+               (insert (substring ts 1 -1) " " hd "\n"))
        (princ (format "BEGIN:VEVENT
 %s
-%s
+%s%s
 SUMMARY:%s
 CATEGORIES:%s
 END:VEVENT\n"
                       (org-ical-ts-to-string ts "DTSTART")
                       (org-ical-ts-to-string ts2 "DTEND" inc)
-                      hd category)))
+                          rrule hd category)))))
+
+      (when (and org-icalendar-include-sexps
+                (condition-case nil (require 'icalendar) (error nil))
+                (fboundp 'icalendar-export-region))
+       ;; Get all the literal sexps
+       (goto-char (point-min))
+       (while (re-search-forward "^&?%%(" nil t)
+         (catch :skip
+           (org-agenda-skip)
+           (setq b (match-beginning 0))
+           (goto-char (1- (match-end 0)))
+           (forward-sexp 1)
+           (end-of-line 1)
+           (setq sexp (buffer-substring b (point)))
+           (with-current-buffer sexp-buffer
+             (insert sexp "\n"))
+           (princ (org-diary-to-ical-string sexp-buffer)))))
+
       (when org-icalendar-include-todo
        (goto-char (point-min))
        (while (re-search-forward org-todo-line-regexp nil t)
+         (catch :skip
+           (org-agenda-skip)
          (setq state (match-string 2))
-         (setq status (if (equal state org-done-string)
+           (setq status (if (member state org-done-keywords)
                           "COMPLETED" "NEEDS-ACTION"))
          (when (and state
-                    (or (not (equal state org-done-string))
-                        (eq org-icalendar-include-todo 'all)))
+                      (or (not (member state org-done-keywords))
+                          (eq org-icalendar-include-todo 'all))
+                      (not (member org-archive-tag (org-get-tags-at)))
+                      )
            (setq hd (match-string 3))
+             (if (string-match org-bracket-link-regexp hd)
+                 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
+                                           (match-string 1 hd))
+                                         t t hd)))
            (if (string-match org-priority-regexp hd)
                (setq pri (string-to-char (match-string 2 hd))
                      hd (concat (substring hd 0 (match-beginning 1))
                                 (substring hd (match-end 1))))
              (setq pri org-default-priority))
            (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
-                                         (- org-lowest-priority ?A))))))
+                                           (- org-lowest-priority 
org-highest-priority))))))
 
            (princ (format "BEGIN:VTODO
 %s
@@ -18420,7 +20197,7 @@
 PRIORITY:%d
 STATUS:%s
 END:VTODO\n"
-                          dts hd category pri status))))))))
+                            dts hd category pri status)))))))))
 
 (defun org-start-icalendar-file (name)
   "Start an iCalendar file by inserting the header."
@@ -18545,47 +20322,44 @@
 
 ;;;; Key bindings
 
-;; - Bindings in Org-mode map are currently
-;;   address@hidden&-+*/=()_{}[]:;"|,.<>~`'\t  the alphabet
-;;             abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/=     [] ; |,.<>~ '\t  
necessary bindings
-;;                 e                                                        
(?) useful from outline-mode
-;;                     i k                 @                                
expendable from outline-mode
-;;   0123456789                               % &     ()_{}    "      `     
free
-
 ;; Make `C-c C-x' a prefix key
-(define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
+(org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
 
 ;; TAB key with modifiers
-(define-key org-mode-map "\C-i"       'org-cycle)
-(define-key org-mode-map [(tab)]      'org-cycle)
-(define-key org-mode-map [(control tab)] 'org-force-cycle-archived)
-(define-key org-mode-map [(meta tab)] 'org-complete)
-(define-key org-mode-map "\M-\t" 'org-complete)
-(define-key org-mode-map "\M-\C-i"      'org-complete)
+(org-defkey org-mode-map "\C-i"       'org-cycle)
+(org-defkey org-mode-map [(tab)]      'org-cycle)
+(org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
+(org-defkey org-mode-map [(meta tab)] 'org-complete)
+(org-defkey org-mode-map "\M-\t" 'org-complete)
+(org-defkey org-mode-map "\M-\C-i"      'org-complete)
 ;; The following line is necessary under Suse GNU/Linux
 (unless (featurep 'xemacs)
-  (define-key org-mode-map [S-iso-lefttab]  'org-shifttab))
-(define-key org-mode-map [(shift tab)]    'org-shifttab)
-
-(define-key org-mode-map (org-key 'S-return)   'org-table-copy-down)
-(define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
-(define-key org-mode-map [(meta return)]       'org-meta-return)
+  (org-defkey org-mode-map [S-iso-lefttab]  'org-shifttab))
+(org-defkey org-mode-map [(shift tab)]    'org-shifttab)
+(define-key org-mode-map (kbd "<backtab>") 'org-shifttab)
+
+(org-defkey org-mode-map [(shift return)]   'org-table-copy-down)
+(org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
+(org-defkey org-mode-map [(meta return)]       'org-meta-return)
 
 ;; Cursor keys with modifiers
-(define-key org-mode-map [(meta left)]  'org-metaleft)
-(define-key org-mode-map [(meta right)] 'org-metaright)
-(define-key org-mode-map [(meta up)]    'org-metaup)
-(define-key org-mode-map [(meta down)]  'org-metadown)
-
-(define-key org-mode-map [(meta shift left)]   'org-shiftmetaleft)
-(define-key org-mode-map [(meta shift right)]  'org-shiftmetaright)
-(define-key org-mode-map [(meta shift up)]     'org-shiftmetaup)
-(define-key org-mode-map [(meta shift down)]   'org-shiftmetadown)
-
-(define-key org-mode-map (org-key 'S-up)       'org-shiftup)
-(define-key org-mode-map (org-key 'S-down)     'org-shiftdown)
-(define-key org-mode-map (org-key 'S-left)     'org-shiftleft)
-(define-key org-mode-map (org-key 'S-right)    'org-shiftright)
+(org-defkey org-mode-map [(meta left)]  'org-metaleft)
+(org-defkey org-mode-map [(meta right)] 'org-metaright)
+(org-defkey org-mode-map [(meta up)]    'org-metaup)
+(org-defkey org-mode-map [(meta down)]  'org-metadown)
+
+(org-defkey org-mode-map [(meta shift left)]   'org-shiftmetaleft)
+(org-defkey org-mode-map [(meta shift right)]  'org-shiftmetaright)
+(org-defkey org-mode-map [(meta shift up)]     'org-shiftmetaup)
+(org-defkey org-mode-map [(meta shift down)]   'org-shiftmetadown)
+
+(org-defkey org-mode-map [(shift up)]          'org-shiftup)
+(org-defkey org-mode-map [(shift down)]        'org-shiftdown)
+(org-defkey org-mode-map [(shift left)]        'org-shiftleft)
+(org-defkey org-mode-map [(shift right)]       'org-shiftright)
+
+(org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
+(org-defkey org-mode-map [(control shift left)]  'org-shiftcontrolleft)
 
 ;;; Extra keys for tty access.
 ;;  We only set them when really needed because otherwise the
@@ -18593,102 +20367,105 @@
 
 (when (or (featurep 'xemacs)   ;; because XEmacs supports multi-device stuff
          (not window-system))
-  (define-key org-mode-map "\C-c\C-xc"    'org-table-copy-down)
-  (define-key org-mode-map "\C-c\C-xM"    'org-insert-todo-heading)
-  (define-key org-mode-map "\C-c\C-xm"    'org-meta-return)
-  (define-key org-mode-map [?\e (return)] 'org-meta-return)
-  (define-key org-mode-map [?\e (left)]   'org-metaleft)
-  (define-key org-mode-map "\C-c\C-xl"    'org-metaleft)
-  (define-key org-mode-map [?\e (right)]  'org-metaright)
-  (define-key org-mode-map "\C-c\C-xr"    'org-metaright)
-  (define-key org-mode-map [?\e (up)]     'org-metaup)
-  (define-key org-mode-map "\C-c\C-xu"    'org-metaup)
-  (define-key org-mode-map [?\e (down)]   'org-metadown)
-  (define-key org-mode-map "\C-c\C-xd"    'org-metadown)
-  (define-key org-mode-map "\C-c\C-xL"    'org-shiftmetaleft)
-  (define-key org-mode-map "\C-c\C-xR"    'org-shiftmetaright)
-  (define-key org-mode-map "\C-c\C-xU"    'org-shiftmetaup)
-  (define-key org-mode-map "\C-c\C-xD"    'org-shiftmetadown)
-  (define-key org-mode-map [?\C-c ?\C-x (up)]    'org-shiftup)
-  (define-key org-mode-map [?\C-c ?\C-x (down)]  'org-shiftdown)
-  (define-key org-mode-map [?\C-c ?\C-x (left)]  'org-shiftleft)
-  (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright))
+  (org-defkey org-mode-map "\C-c\C-xc"    'org-table-copy-down)
+  (org-defkey org-mode-map "\C-c\C-xM"    'org-insert-todo-heading)
+  (org-defkey org-mode-map "\C-c\C-xm"    'org-meta-return)
+  (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
+  (org-defkey org-mode-map [?\e (left)]   'org-metaleft)
+  (org-defkey org-mode-map "\C-c\C-xl"    'org-metaleft)
+  (org-defkey org-mode-map [?\e (right)]  'org-metaright)
+  (org-defkey org-mode-map "\C-c\C-xr"    'org-metaright)
+  (org-defkey org-mode-map [?\e (up)]     'org-metaup)
+  (org-defkey org-mode-map "\C-c\C-xu"    'org-metaup)
+  (org-defkey org-mode-map [?\e (down)]   'org-metadown)
+  (org-defkey org-mode-map "\C-c\C-xd"    'org-metadown)
+  (org-defkey org-mode-map "\C-c\C-xL"    'org-shiftmetaleft)
+  (org-defkey org-mode-map "\C-c\C-xR"    'org-shiftmetaright)
+  (org-defkey org-mode-map "\C-c\C-xU"    'org-shiftmetaup)
+  (org-defkey org-mode-map "\C-c\C-xD"    'org-shiftmetadown)
+  (org-defkey org-mode-map [?\C-c (up)]    'org-shiftup)
+  (org-defkey org-mode-map [?\C-c (down)]  'org-shiftdown)
+  (org-defkey org-mode-map [?\C-c (left)]  'org-shiftleft)
+  (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
+  (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
+  (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
 
   ;; All the other keys
 
-(define-key org-mode-map "\C-c\C-a" 'show-all)  ; in case allout messed up.
-(define-key org-mode-map "\C-c\C-r" 'org-reveal)
-(define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
-(define-key org-mode-map "\C-c$"    'org-archive-subtree)
-(define-key org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
-(define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
-(define-key org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
-(define-key org-mode-map "\C-c\C-j" 'org-goto)
-(define-key org-mode-map "\C-c\C-t" 'org-todo)
-(define-key org-mode-map "\C-c\C-s" 'org-schedule)
-(define-key org-mode-map "\C-c\C-d" 'org-deadline)
-(define-key org-mode-map "\C-c;"    'org-toggle-comment)
-(define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
-(define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
-(define-key org-mode-map "\C-c/"    'org-occur)   ; Minor-mode reserved
-(define-key org-mode-map "\C-c\\"   'org-tags-sparse-tree) ; Minor-mode res.
-(define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
-(define-key org-mode-map "\M-\C-m"  'org-insert-heading)
-(define-key org-mode-map "\C-c\C-x\C-n" 'org-next-link)
-(define-key org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
-(define-key org-mode-map "\C-c\C-l" 'org-insert-link)
-(define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
-(define-key org-mode-map "\C-c%"    'org-mark-ring-push)
-(define-key org-mode-map "\C-c&"    'org-mark-ring-goto)
-(define-key org-mode-map "\C-c\C-z" 'org-time-stamp)  ; Alternative binding
-(define-key org-mode-map "\C-c."    'org-time-stamp)  ; Minor-mode reserved
-(define-key org-mode-map "\C-c!"    'org-time-stamp-inactive) ; Minor-mode r.
-(define-key org-mode-map "\C-c,"    'org-priority)    ; Minor-mode reserved
-(define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
-(define-key org-mode-map "\C-c>"    'org-goto-calendar)
-(define-key org-mode-map "\C-c<"    'org-date-from-calendar)
-(define-key org-mode-map [(control ?,)]     'org-cycle-agenda-files)
-(define-key org-mode-map [(control ?\')]     'org-cycle-agenda-files)
-(define-key org-mode-map "\C-c["    'org-agenda-file-to-front)
-(define-key org-mode-map "\C-c]"    'org-remove-file)
-(define-key org-mode-map "\C-c-"    'org-table-insert-hline)
-(define-key org-mode-map "\C-c^"    'org-sort)
-(define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
-(define-key org-mode-map "\C-c#"    'org-update-checkbox-count)
-(define-key org-mode-map "\C-m"     'org-return)
-(define-key org-mode-map "\C-c?"    'org-table-field-info)
-(define-key org-mode-map "\C-c "    'org-table-blank-field)
-(define-key org-mode-map "\C-c+"    'org-table-sum)
-(define-key org-mode-map "\C-c="    'org-table-eval-formula)
-(define-key org-mode-map "\C-c'"    'org-table-edit-formulas)
-(define-key org-mode-map "\C-c`"    'org-table-edit-field)
-(define-key org-mode-map "\C-c|"    'org-table-create-or-convert-from-region)
-(define-key org-mode-map "\C-c*"    'org-table-recalculate)
-(define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
-(define-key org-mode-map "\C-c~"    'org-table-create-with-table.el)
-(define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
-(define-key org-mode-map "\C-c}"    'org-table-toggle-coordinate-overlays)
-(define-key org-mode-map "\C-c{"    'org-table-toggle-formula-debugger)
-(define-key org-mode-map "\C-c\C-e" 'org-export)
-(define-key org-mode-map "\C-c:"    'org-toggle-fixed-width-section)
-
-(define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
-(define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
-(define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
-(define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
-
-(define-key org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
-(define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
-(define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
-(define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
-(define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
-(define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
-(define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
-(define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
-(define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
+(org-defkey org-mode-map "\C-c\C-a" 'show-all)  ; in case allout messed up.
+(org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
+(org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
+(org-defkey org-mode-map "\C-c$"    'org-archive-subtree)
+(org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
+(org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
+(org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
+(org-defkey org-mode-map "\C-c\C-j" 'org-goto)
+(org-defkey org-mode-map "\C-c\C-t" 'org-todo)
+(org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
+(org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
+(org-defkey org-mode-map "\C-c;"    'org-toggle-comment)
+(org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
+(org-defkey org-mode-map "\C-c\C-w" 'org-check-deadlines)
+(org-defkey org-mode-map "\C-c/"    'org-occur)   ; Minor-mode reserved
+(org-defkey org-mode-map "\C-c\\"   'org-tags-sparse-tree) ; Minor-mode res.
+(org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
+(org-defkey org-mode-map "\M-\C-m"  'org-insert-heading)
+(org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
+(org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
+(org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
+(org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
+(org-defkey org-mode-map "\C-c%"    'org-mark-ring-push)
+(org-defkey org-mode-map "\C-c&"    'org-mark-ring-goto)
+(org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp)  ; Alternative binding
+(org-defkey org-mode-map "\C-c."    'org-time-stamp)  ; Minor-mode reserved
+(org-defkey org-mode-map "\C-c!"    'org-time-stamp-inactive) ; Minor-mode r.
+(org-defkey org-mode-map "\C-c,"    'org-priority)    ; Minor-mode reserved
+(org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
+(org-defkey org-mode-map "\C-c>"    'org-goto-calendar)
+(org-defkey org-mode-map "\C-c<"    'org-date-from-calendar)
+(org-defkey org-mode-map [(control ?,)]     'org-cycle-agenda-files)
+(org-defkey org-mode-map [(control ?\')]     'org-cycle-agenda-files)
+(org-defkey org-mode-map "\C-c["    'org-agenda-file-to-front)
+(org-defkey org-mode-map "\C-c]"    'org-remove-file)
+(org-defkey org-mode-map "\C-c-"    'org-table-insert-hline)
+(org-defkey org-mode-map "\C-c^"    'org-sort)
+(org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
+(org-defkey org-mode-map "\C-c#"    'org-update-checkbox-count)
+(org-defkey org-mode-map "\C-m"     'org-return)
+(org-defkey org-mode-map "\C-c?"    'org-table-field-info)
+(org-defkey org-mode-map "\C-c "    'org-table-blank-field)
+(org-defkey org-mode-map "\C-c+"    'org-table-sum)
+(org-defkey org-mode-map "\C-c="    'org-table-eval-formula)
+(org-defkey org-mode-map "\C-c'"    'org-table-edit-formulas)
+(org-defkey org-mode-map "\C-c`"    'org-table-edit-field)
+(org-defkey org-mode-map "\C-c|"    'org-table-create-or-convert-from-region)
+(org-defkey org-mode-map "\C-c*"    'org-table-recalculate)
+(org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
+(org-defkey org-mode-map "\C-c~"    'org-table-create-with-table.el)
+(org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
+(org-defkey org-mode-map "\C-c}"    'org-table-toggle-coordinate-overlays)
+(org-defkey org-mode-map "\C-c{"    'org-table-toggle-formula-debugger)
+(org-defkey org-mode-map "\C-c\C-e" 'org-export)
+(org-defkey org-mode-map "\C-c:"    'org-toggle-fixed-width-section)
+(org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
+
+(org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
+(org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
+(org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
+(org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
+
+(org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
+(org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
+(org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
+(org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
+(org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
+(org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
+(org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
+(org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
+(org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
 
 (when (featurep 'xemacs)
-  (define-key org-mode-map 'button3   'popup-mode-menu))
+  (org-defkey org-mode-map 'button3   'popup-mode-menu))
 
 (defsubst org-table-p () (org-at-table-p))
 
@@ -18779,7 +20556,6 @@
 (put 'org-delete-char 'flyspell-delayed t)
 (put 'org-delete-backward-char 'flyspell-delayed t)
 
-
 ;; How to do this: Measure non-white length of current string
 ;; If equal to column width, we should realign.
 
@@ -18790,7 +20566,7 @@
     (while commands
       (setq old (pop commands) new (pop commands))
       (if (fboundp 'command-remapping)
-         (define-key map (vector 'remap old) new)
+         (org-defkey map (vector 'remap old) new)
        (substitute-key-definition old new map global-map)))))
 
 (when (eq org-enable-table-editor 'optimized)
@@ -18800,7 +20576,7 @@
             'self-insert-command 'org-self-insert-command
             'delete-char 'org-delete-char
             'delete-backward-char 'org-delete-backward-char)
-  (define-key org-mode-map "|" 'org-force-self-insert))
+  (org-defkey org-mode-map "|" 'org-force-self-insert))
 
 (defun org-shiftcursor-error ()
   "Throw an error because Shift-Cursor command was applied in wrong context."
@@ -18821,7 +20597,8 @@
 
 (defun org-shiftmetaleft ()
   "Promote subtree or delete table column.
-Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
+Calls `org-promote-subtree', `org-outdent-item',
+or `org-table-delete-column', depending on context.
 See the individual commands for more information."
   (interactive)
   (cond
@@ -18832,7 +20609,8 @@
 
 (defun org-shiftmetaright ()
   "Demote subtree or insert table column.
-Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
+Calls `org-demote-subtree', `org-indent-item',
+or `org-table-insert-column', depending on context.
 See the individual commands for more information."
   (interactive)
   (cond
@@ -18916,8 +20694,8 @@
 
 (defun org-shiftup (&optional arg)
   "Increase item in timestamp or increase priority of current headline.
-Calls `org-timestamp-up' or `org-priority-up', depending on context.
-See the individual commands for more information."
+Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
+depending on context.  See the individual commands for more information."
   (interactive "P")
   (cond
    ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
@@ -18927,8 +20705,8 @@
 
 (defun org-shiftdown (&optional arg)
   "Decrease item in timestamp or decrease priority of current headline.
-Calls `org-timestamp-down' or `org-priority-down', depending on context.
-See the individual commands for more information."
+Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
+depending on context.  See the individual commands for more information."
   (interactive "P")
   (cond
    ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
@@ -18951,6 +20729,27 @@
    ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
    (t (org-shiftcursor-error))))
 
+(defun org-shiftcontrolright ()
+  "Switch to next TODO set."
+  (interactive)
+  (cond
+   ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
+   (t (org-shiftcursor-error))))
+
+(defun org-shiftcontrolleft ()
+  "Switch to previous TODO set."
+  (interactive)
+  (cond
+   ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
+   (t (org-shiftcursor-error))))
+
+(defun org-ctrl-c-ret ()
+  "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
+  (interactive)
+  (cond
+   ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
+   (t (call-interactively 'org-insert-heading))))
+
 (defun org-copy-special ()
   "Copy region in table or copy current subtree.
 Calls `org-table-copy' or `org-copy-subtree', depending on context.
@@ -19159,7 +20958,11 @@
      ["Next Same Level" outline-forward-same-level t]
      ["Previous Same Level" outline-backward-same-level t]
      "--"
-     ["Jump" org-goto t])
+     ["Jump" org-goto t]
+     "--"
+     ["C-a finds headline start"
+      (setq org-special-ctrl-a (not org-special-ctrl-a))
+      :style toggle :selected org-special-ctrl-a])
     ("Edit Structure"
      ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
      ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
@@ -19177,6 +20980,8 @@
      "--"
      ["Convert to odd levels" org-convert-to-odd-levels t]
      ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
+    ("Editing"
+     ["Emphasis..." org-emphasize t])
     ("Archive"
      ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
 ;     ["Check and Tag Children" (org-toggle-archive-tag (4))
@@ -19202,7 +21007,9 @@
      ("Select keyword"
       ["Next keyword" org-shiftright (org-on-heading-p)]
       ["Previous keyword" org-shiftleft (org-on-heading-p)]
-      ["Complete Keyword" org-complete (assq :todo-keyword (org-context))])
+      ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
+      ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 
1) (org-on-heading-p))]
+      ["Previous keyword set" org-shiftcontrolright (and (> (length 
org-todo-sets) 1) (org-on-heading-p))])
      ["Show TODO Tree" org-show-todo-tree t]
      ["Global TODO list" org-todo-list t]
      "--"
@@ -19210,6 +21017,7 @@
      ["Priority Up" org-shiftup t]
      ["Priority Down" org-shiftdown t]
      "--"
+     ;; FIXME:  why is this still here????
 ;     ["Insert Checkbox" org-insert-todo-heading (org-in-item-p)]
 ;     ["Toggle Checkbox" org-ctrl-c-ctrl-c (org-at-item-checkbox-p)]
 ;     ["Insert [n/m] cookie" (progn (insert "[/]") (org-update-checkbox-count))
@@ -19245,7 +21053,7 @@
      ["Record DONE time"
       (progn (setq org-log-done (not org-log-done))
             (message "Switching to %s will %s record a timestamp"
-                     org-done-string
+                     (car org-done-keywords)
                      (if org-log-done "automatically" "not")))
       :style toggle :selected org-log-done])
     "--"
@@ -19297,15 +21105,6 @@
     ["Refresh setup" org-mode-restart t]
     ))
 
-(defun org-toggle-log-option (type)
-  (if (not (listp org-log-done)) (setq org-log-done nil))
-  (if (memq type org-log-done)
-      (setq org-log-done (delq type org-log-done))
-    (add-to-list 'org-log-done type)))
-
-(defun org-check-log-option (type)
-  (and (listp org-log-done) (memq type org-log-done)))
-
 (defun org-info (&optional node)
   "Read documentation for Org-mode in the info system.
 With optional NODE, go directly to that node."
@@ -19394,7 +21193,7 @@
         (p (point)) clist o)
     ;; First the large context
     (cond
-     ((org-on-heading-p)
+     ((org-on-heading-p t)
       (push (list :headline (point-at-bol) (point-at-eol)) clist)
       (when (progn
              (beginning-of-line 1)
@@ -19404,7 +21203,7 @@
        (push (org-point-in-group p 4 :tags) clist))
       (goto-char p)
       (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
-      (if (looking-at "\\[#[A-Z]\\]")
+      (if (looking-at "\\[#[A-Z0-9]\\]")
          (push (org-point-in-group p 0 :priority) clist)))
 
      ((org-at-item-p)
@@ -19459,6 +21258,7 @@
     (setq clist (nreverse (delq nil clist)))
     clist))
 
+;; FIXME Compare with at-regexp-p
 (defun org-in-regexp (re &optional nlines visually)
   "Check if point is inside a match of regexp.
 Normally only the current line is checked, but you can include NLINES extra
@@ -19476,6 +21276,30 @@
                   (>= (+ inc (match-end 0)) pos))
              (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
 
+(defun org-at-regexp-p (regexp)
+  "Is point inside a match of REGEXP in the current line?"
+  (catch 'exit
+    (save-excursion
+      (let ((pos (point)) (end (point-at-eol)))
+       (beginning-of-line 1)
+       (while (re-search-forward regexp end t)
+         (if (and (<= (match-beginning 0) pos)
+                  (>= (match-end 0) pos))
+             (throw 'exit t)))
+       nil))))
+
+(defun org-uniquify (list)
+  "Remove duplicate elements from LIST."
+  (let (res)
+    (mapc (lambda (x) (add-to-list 'res x 'append)) list)
+    res))
+
+(defun org-delete-all (elts list)
+  "Remove all elements in ELTS from LIST."
+  (while elts
+    (setq list (delete (pop elts) list)))
+  list)
+
 (defun org-point-in-group (point group &optional context)
   "Check if POINT is in match-group GROUP.
 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
@@ -19555,27 +21379,49 @@
       (setq c (1+ c)))
     (nreverse rtn)))
 
-(defun org-at-regexp-p (regexp)
-  "Is point inside a match of REGEXP in the current line?"
-  (catch 'exit
-    (save-excursion
-      (let ((pos (point)) (end (point-at-eol)))
-       (beginning-of-line 1)
-       (while (re-search-forward regexp end t)
-         (if (and (<= (match-beginning 0) pos)
-                  (>= (match-end 0) pos))
-             (throw 'exit t)))
-       nil))))
-
 (defun org-find-base-buffer-visiting (file)
   "Like `find-buffer-visiting' but alway return the base buffer and
 not an indirect buffer"
   (let ((buf (find-buffer-visiting file)))
     (or (buffer-base-buffer buf) buf)))
 
+(defun org-image-file-name-regexp ()
+  "Return regexp matching the file names of images."
+  (if (fboundp 'image-file-name-regexp)
+      (image-file-name-regexp)
+    (let ((image-file-name-extensions
+          '("png" "jpeg" "jpg" "gif" "tiff" "tif"
+            "xbm" "xpm" "pbm" "pgm" "ppm")))
+      (concat "\\."
+             (regexp-opt (nconc (mapcar 'upcase
+                                        image-file-name-extensions)
+                                image-file-name-extensions)
+                         t)
+             "\\'"))))
+
+(defun org-file-image-p (file)
+  "Return non-nil if FILE is an image."
+  (save-match-data
+    (string-match (org-image-file-name-regexp) file)))
+
 ;;; Paragraph filling stuff.
 ;; We want this to be just right, so use the full arsenal.
-;; FIXME: configure filladapt for XEmacs
+
+(defun org-indent-line-function ()
+  "Indent line like previous, but further if previous was headline or item."
+  (interactive)
+  (let ((column (save-excursion
+                 (beginning-of-line)
+                 (if (looking-at "#") 0
+                   (skip-chars-backward "\n \t")
+                   (beginning-of-line)
+                   (if (or (looking-at "\\*+[ \t]+")
+                           (looking-at "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ 
\t]+\\)"))
+                       (progn (goto-char (match-end 0)) (current-column))
+                     (current-indentation))))))
+    (if (<= (current-column) (current-indentation))
+       (indent-line-to column)
+      (save-excursion (indent-line-to column)))))
 
 (defun org-set-autofill-regexps ()
   (interactive)
@@ -19584,6 +21430,7 @@
   ;; fill the headline as well.
   (org-set-local 'comment-start-skip "^#+[ \t]*")
   (org-set-local 'paragraph-separate "\f\\|\\*\\|[     ]*$\\|[ \t]*[:|]")
+;; FIXME!!!!!!!  (org-set-local 'paragraph-separate "\f\\|[    ]*$")
   ;; The paragraph starter includes hand-formatted lists.
   (org-set-local 'paragraph-start
                 "\f\\|[        ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ 
\t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
@@ -19627,30 +21474,12 @@
 work correctly."
   (cond ((looking-at "#[ \t]+")
         (match-string 0))
-       ((looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
-        (make-string (- (match-end 0) (match-beginning 0)) ?\ ))
+       ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
+        (save-excursion
+          (goto-char (match-end 0))
+          (make-string (current-column) ?\ )))
        (t nil)))
 
-
-(defun org-image-file-name-regexp ()
-  "Return regexp matching the file names of images."
-  (if (fboundp 'image-file-name-regexp)
-      (image-file-name-regexp)
-    (let ((image-file-name-extensions
-          '("png" "jpeg" "jpg" "gif" "tiff" "tif"
-            "xbm" "xpm" "pbm" "pgm" "ppm")))
-      (concat "\\."
-             (regexp-opt (nconc (mapcar 'upcase
-                                        image-file-name-extensions)
-                                image-file-name-extensions)
-                         t)
-             "\\'"))))
-
-(defun org-file-image-p (file)
-  "Return non-nil if FILE is an image."
-  (save-match-data
-    (string-match (org-image-file-name-regexp) file)))
-
 ;;;; Functions extending outline functionality
 
 ;; C-a should go to the beginning of a *visible* line, also in the
@@ -19659,6 +21488,7 @@
   "Go to the beginning of the current line.  If that is invisible, continue
 to a visible line beginning.  This makes the function of C-a more intuitive."
   (interactive)
+  (let ((pos (point)))
   (beginning-of-line 1)
   (if (bobp)
       nil
@@ -19667,7 +21497,13 @@
        (while (and (not (bobp)) (org-invisible-p))
          (backward-char 1)
          (beginning-of-line 1))
-      (forward-char 1))))
+       (forward-char 1)))
+    (when (and org-special-ctrl-a (looking-at org-todo-line-regexp)
+              (= (char-after (match-end 1)) ?\ ))
+      (goto-char
+       (cond ((> pos (match-beginning 3)) (match-beginning 3))
+            ((= pos (point)) (match-beginning 3))
+            (t (point)))))))
 
 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
 
@@ -19689,6 +21525,9 @@
 
 (defalias 'org-back-to-heading 'outline-back-to-heading)
 (defalias 'org-on-heading-p 'outline-on-heading-p)
+(defalias 'org-at-heading-p 'outline-on-heading-p)
+(defun org-at-heading-or-item-p ()
+  (or (org-on-heading-p) (org-at-item-p)))
 
 (defun org-on-target-p ()
   (or (org-in-regexp org-radio-target-regexp)
@@ -19751,7 +21590,7 @@
                           (save-excursion (outline-end-of-heading) (point))
                           flag))))
 
-(defun org-end-of-subtree (&optional invisible-OK)
+(defun org-end-of-subtree (&optional invisible-OK to-heading)
   ;; This is an exact copy of the original function, but it uses
   ;; `org-back-to-heading', to make it work also in invisible
   ;; trees.  And is uses an invisible-OK argument.
@@ -19763,13 +21602,14 @@
                (or first (> (funcall outline-level) level)))
       (setq first nil)
       (outline-next-heading))
+    (unless to-heading
     (if (memq (preceding-char) '(?\n ?\^M))
        (progn
          ;; Go to end of line before heading
          (forward-char -1)
          (if (memq (preceding-char) '(?\n ?\^M))
              ;; leave blank line before heading
-             (forward-char -1)))))
+               (forward-char -1))))))
   (point))
 
 (defun org-show-subtree ()
@@ -19824,7 +21664,13 @@
   (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
   (org-show-context 'isearch))
 
-;;;; Repair problems with some other packages
+
+;;;; Address problems with some other packages
+
+;; Make flyspell not check words in links, to not mess up our keymap
+(defun org-mode-flyspell-verify ()
+  "Don't let flyspell put overlays at active buttons."
+  (not (get-text-property (point) 'keymap)))
 
 ;; Make `bookmark-jump' show the jump location if it was hidden.
 (eval-after-load "bookmark"
@@ -19850,6 +21696,26 @@
 
 ;;;; Experimental code
 
+(defun org-closed-in-range ()
+  "Sparse tree of items closed in a certain time range.
+Still experimental, may disappear in the furture."
+  (interactive)
+  ;; Get the time interval from the user.
+  (let* ((time1 (time-to-seconds
+                 (org-read-date nil 'to-time nil "Starting date: ")))
+         (time2 (time-to-seconds
+                 (org-read-date nil 'to-time nil "End date:")))
+         ;; callback function
+         (callback (lambda ()
+                     (let ((time
+                            (time-to-seconds
+                             (apply 'encode-time
+                                    (org-parse-time-string
+                                     (match-string 1))))))
+                       ;; check if time in interval
+                       (and (>= time time1) (<= time time2))))))
+    ;; make tree, check each match with the callback
+    (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
 
 ;;;; Finish up
 




reply via email to

[Prev in Thread] Current Thread [Next in Thread]