Update to Org mode 7.4
[bpt/emacs.git] / lisp / org / org.el
index 82838bb..eb91968 100644 (file)
@@ -1,12 +1,12 @@
 ;;; org.el --- Outline-based notes management and organizer
 ;; Carstens outline-mode for keeping track of everything.
-;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
+;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010
 ;;   Free Software Foundation, Inc.
 ;;
 ;; Author: Carsten Dominik <carsten at orgmode dot org>
 ;; Keywords: outlines, hypermedia, calendar, wp
 ;; Homepage: http://orgmode.org
-;; Version: 6.30c
+;; Version: 7.4
 ;;
 ;; This file is part of GNU Emacs.
 ;;
 
 (eval-when-compile
   (require 'cl)
-  (require 'gnus-sum)
-  (require 'calendar))
-;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
-;; the file noutline.el being loaded.
-(if (featurep 'xemacs) (condition-case nil (require 'noutline)))
-;; We require noutline, which might be provided in outline.el
+  (require 'gnus-sum))
+
+(require 'calendar)
+
+;; Emacs 22 calendar compatibility:  Make sure the new variables are available
+(when (fboundp 'defvaralias)
+  (unless (boundp 'calendar-view-holidays-initially-flag)
+    (defvaralias 'calendar-view-holidays-initially-flag
+      'view-calendar-holidays-initially))
+  (unless (boundp 'calendar-view-diary-initially-flag)
+    (defvaralias 'calendar-view-diary-initially-flag
+      'view-diary-entries-initially))
+  (unless (boundp 'diary-fancy-buffer)
+    (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
+
 (require 'outline) (require 'noutline)
 ;; Other stuff we need.
 (require 'time-date)
 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
 (require 'easymenu)
+(require 'overlay)
 
 (require 'org-macs)
+(require 'org-entities)
 (require 'org-compat)
 (require 'org-faces)
 (require 'org-list)
+(require 'org-complete)
 (require 'org-src)
 (require 'org-footnote)
 
+;; babel
+(require 'ob)
+(require 'ob-table)
+(require 'ob-lob)
+(require 'ob-ref)
+(require 'ob-tangle)
+(require 'ob-comint)
+(require 'ob-keys)
+
+;; load languages based on value of `org-babel-load-languages'
+(defvar org-babel-load-languages)
+;;;###autoload
+(defun org-babel-do-load-languages (sym value)
+  "Load the languages defined in `org-babel-load-languages'."
+  (set-default sym value)
+  (mapc (lambda (pair)
+         (let ((active (cdr pair)) (lang (symbol-name (car pair))))
+           (if active
+               (progn
+                 (require (intern (concat "ob-" lang))))
+             (progn
+               (funcall 'fmakunbound
+                        (intern (concat "org-babel-execute:" lang)))
+               (funcall 'fmakunbound
+                        (intern (concat "org-babel-expand-body:" lang)))))))
+       org-babel-load-languages))
+
+(defcustom org-babel-load-languages '((emacs-lisp . t))
+  "Languages which can be evaluated in Org-mode buffers.
+This list can be used to load support for any of the languages
+below, note that each language will depend on a different set of
+system executables and/or Emacs modes.  When a language is
+\"loaded\", then code blocks in that language can be evaluated
+with `org-babel-execute-src-block' bound by default to C-c
+C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
+be set to remove code block evaluation from the C-c C-c
+keybinding.  By default only Emacs Lisp (which has no
+requirements) is loaded."
+  :group 'org-babel
+  :set 'org-babel-do-load-languages
+  :type '(alist :tag "Babel Languages"
+               :key-type
+               (choice
+                (const :tag "C" C)
+                (const :tag "R" R)
+                (const :tag "Asymptote" asymptote)
+                (const :tag "Calc" calc)
+                (const :tag "Clojure" clojure)
+                (const :tag "CSS" css)
+                (const :tag "Ditaa" ditaa)
+                (const :tag "Dot" dot)
+                (const :tag "Emacs Lisp" emacs-lisp)
+                (const :tag "Gnuplot" gnuplot)
+                (const :tag "Haskell" haskell)
+                (const :tag "Javascript" js)
+                (const :tag "Latex" latex)
+                (const :tag "Ledger" ledger)
+                (const :tag "Matlab" matlab)
+                (const :tag "Mscgen" mscgen)
+                (const :tag "Ocaml" ocaml)
+                (const :tag "Octave" octave)
+                (const :tag "Org" org)
+                (const :tag "Perl" perl)
+                (const :tag "PlantUML" plantuml)
+                (const :tag "Python" python)
+                (const :tag "Ruby" ruby)
+                (const :tag "Sass" sass)
+                (const :tag "Scheme" scheme)
+                (const :tag "Screen" screen)
+                (const :tag "Shell Script" sh)
+                (const :tag "Sql" sql)
+                (const :tag "Sqlite" sqlite))
+               :value-type (boolean :tag "Activate" :value t)))
+
 ;;;; Customization variables
+(defcustom org-clone-delete-id nil
+  "Remove ID property of clones of a subtree.
+When non-nil, clones of a subtree don't inherit the ID property.
+Otherwise they inherit the ID property with a new unique
+identifier."
+  :type 'boolean
+  :group 'org-id)
 
 ;;; Version
 
-(defconst org-version "6.30c"
+(defconst org-version "7.4"
   "The version number of the file org.el.")
 
 (defun org-version (&optional here)
   "Show the org-mode version in the echo area.
 With prefix arg HERE, insert it at point."
   (interactive "P")
-  (let* ((version org-version)
+  (let* ((origin default-directory)
+        (version org-version)
         (git-version)
         (dir (concat (file-name-directory (locate-library "org")) "../" )))
-    (if (and (file-exists-p (expand-file-name ".git" dir))
-            (executable-find "git"))
-       (let ((pwd (substring (pwd) 10)))
-         (cd dir)
-         (if (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
-             (save-excursion
-               (set-buffer "*Shell Command Output*")
+    (when (and (file-exists-p (expand-file-name ".git" dir))
+              (executable-find "git"))
+      (unwind-protect
+         (progn
+           (cd dir)
+           (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
+             (with-current-buffer "*Shell Command Output*"
                (goto-char (point-min))
-               (re-search-forward "[^\n]+")
-               (setq git-version (match-string 0))
-               (subst-char-in-string ?- ?. git-version t)
-               (shell-command "git diff-index --name-only HEAD --")
-               (unless (eql 1 (point-max))
-                 (setq git-version (concat git-version ".dirty")))
-               (setq version (concat version " (" git-version ")")))
-           (cd pwd))))
+               (setq git-version (buffer-substring (point) (point-at-eol))))
+             (subst-char-in-string ?- ?. git-version t)
+             (when (string-match "\\S-"
+                                 (shell-command-to-string
+                                  "git diff-index --name-only HEAD --"))
+               (setq git-version (concat git-version ".dirty")))
+             (setq version (concat version " (" git-version ")"))))
+       (cd origin)))
     (setq version (format "Org-mode version %s" version))
     (if here (insert version))
-    (message version)
-    version))
+    (message version)))
 
 ;;; Compatibility constants
 
@@ -134,9 +227,13 @@ With prefix arg HERE, insert it at point."
   "Outline-based notes management and organizer."
   :tag "Org"
   :group 'outlines
-  :group 'hypermedia
   :group 'calendar)
 
+(defcustom org-mode-hook nil
+  "Mode hook for Org-mode, run after the mode was turned on."
+  :group 'org
+  :type 'hook)
+
 (defcustom org-load-hook nil
   "Hook that is run after org.el has been loaded."
   :group 'org
@@ -165,14 +262,14 @@ With prefix arg HERE, insert it at point."
   (let ((a (member 'org-infojs org-modules)))
     (and a (setcar a 'org-jsinfo))))
 
-(defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
+(defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
   "Modules that should always be loaded together with org.el.
 If a description starts with <C>, the file is not part of Emacs
 and loading it will require that you have downloaded and properly installed
 the org-mode distribution.
 
 You can also use this system to load external packages (i.e. neither Org
-core modules, not modules from the CONTRIB directory).  Just add symbols
+core modules, nor modules from the CONTRIB directory).  Just add symbols
 to the end of the list.  If the package is called org-xyz.el, then you need
 to add the symbol `xyz', and the package must have a call to
 
@@ -183,10 +280,14 @@ to add the symbol `xyz', and the package must have a call to
   '(set :greedy t
        (const :tag "   bbdb:              Links to BBDB entries" org-bbdb)
        (const :tag "   bibtex:            Links to BibTeX entries" org-bibtex)
+       (const :tag "   crypt:             Encryption of subtrees" org-crypt)
+       (const :tag "   ctags:             Access to Emacs tags with links" org-ctags)
+       (const :tag "   docview:           Links to doc-view buffers" org-docview)
        (const :tag "   gnus:              Links to GNUS folders/messages" org-gnus)
        (const :tag "   id:                Global IDs for identifying entries" org-id)
        (const :tag "   info:              Links to Info nodes" org-info)
        (const :tag "   jsinfo:            Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
+       (const :tag "   habit:             Track your consistency with habits" org-habit)
        (const :tag "   inlinetask:        Tasks independent of outline hierarchy" org-inlinetask)
        (const :tag "   irc:               Links to IRC/ERC chat sessions" org-irc)
        (const :tag "   mac-message:       Links to messages in Apple Mail" org-mac-message)
@@ -196,44 +297,51 @@ to add the symbol `xyz', and the package must have a call to
        (const :tag "   rmail:             Links to RMAIL folders/messages" org-rmail)
        (const :tag "   vm:                Links to VM folders/messages" org-vm)
        (const :tag "   wl:                Links to Wanderlust folders/messages" org-wl)
-       (const :tag "   w3m:               Special cut/paste from w3m to Org." org-w3m)
+       (const :tag "   w3m:               Special cut/paste from w3m to Org-mode." org-w3m)
        (const :tag "   mouse:             Additional mouse support" org-mouse)
+       (const :tag "   TaskJuggler:       Export tasks to a TaskJuggler project" org-taskjuggler)
 
        (const :tag "C  annotate-file:     Annotate a file with org syntax" org-annotate-file)
-       (const :tag "C  annotation-helper: Call Remember directly from Browser (OBSOLETE, use org-protocol)" org-annotation-helper)
-       (const :tag "C  bookmark:          Org links to bookmarks" org-bookmark)
-       (const :tag "C  browser-url:       Store link, directly from Browser (OBSOLETE, use org-protocol)" org-browser-url)
+       (const :tag "C  bookmark:          Org-mode links to bookmarks" org-bookmark)
        (const :tag "C  checklist:         Extra functions for checklists in repeated tasks" org-checklist)
        (const :tag "C  choose:            Use TODO keywords to mark decisions states" org-choose)
        (const :tag "C  collector:         Collect properties into tables" org-collector)
-       (const :tag "C  depend:            TODO dependencies for Org-mode (PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
-       (const :tag "C  elisp-symbol:      Org links to emacs-lisp symbols" org-elisp-symbol)
+       (const :tag "C  depend:            TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
+       (const :tag "C  elisp-symbol:      Org-mode links to emacs-lisp symbols" org-elisp-symbol)
        (const :tag "C  eval:              Include command output as text" org-eval)
        (const :tag "C  eval-light:        Evaluate inbuffer-code on demand" org-eval-light)
-       (const :tag "C  expiry:            Expiry mechanism for Org entries" org-expiry)
+       (const :tag "C  expiry:            Expiry mechanism for Org-mode entries" org-expiry)
        (const :tag "C  exp-bibtex:        Export citations using BibTeX" org-exp-bibtex)
-       (const :tag "C  interactive-query: Interactive modification of tags query (PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
-       (const :tag "C  jira               Add a jira:ticket protocol to Org" org-jira)
-       (const :tag "C  mairix:            Hook mairix search into Org for different MUAs" org-mairix)
+       (const :tag "C  git-link:          Provide org links to specific file version" org-git-link)
+       (const :tag "C  interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
+
+        (const :tag "C  invoice:           Help manage client invoices in Org-mode" org-invoice)
+
+       (const :tag "C  jira:              Add a jira:ticket protocol to Org-mode" org-jira)
+       (const :tag "C  learn:             SuperMemo's incremental learning algorithm" org-learn)
+       (const :tag "C  mairix:            Hook mairix search into Org-mode for different MUAs" org-mairix)
        (const :tag "C  mac-iCal           Imports events from iCal.app to the Emacs diary" org-mac-iCal)
+       (const :tag "C  mac-link-grabber   Grab links and URLs from various Mac applications" org-mac-link-grabber)
        (const :tag "C  man:               Support for links to manpages in Org-mode" org-man)
        (const :tag "C  mtags:             Support for muse-like tags" org-mtags)
        (const :tag "C  panel:             Simple routines for us with bad memory" org-panel)
-       (const :tag "C  R:                 Computation using the R language" org-R)
-       (const :tag "C  registry:          A registry for Org links" org-registry)
+       (const :tag "C  registry:          A registry for Org-mode links" org-registry)
        (const :tag "C  org2rem:           Convert org appointments into reminders" org2rem)
        (const :tag "C  screen:            Visit screen sessions through Org-mode links" org-screen)
+       (const :tag "C  secretary:         Team management with org-mode" org-secretary)
        (const :tag "C  special-blocks:    Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
        (const :tag "C  sqlinsert:         Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
        (const :tag "C  toc:               Table of contents for Org-mode buffer" org-toc)
-       (const :tag "C  track:             Keep up with Org development" org-track)
+       (const :tag "C  track:             Keep up with Org-mode development" org-track)
+       (const :tag "C  velocity           Something like Notational Velocity for Org" org-velocity)
+       (const :tag "C  wikinodes:         CamelCase wiki-like links" org-wikinodes)
        (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
 
 (defcustom org-support-shift-select nil
-  "Non-nil means, make shift-cursor commands select text when possible.
+  "Non-nil means make shift-cursor commands select text when possible.
 
 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
-selecting a region, or enlarge thusly regions started in this way.
+selecting a region, or enlarge regions started in this way.
 In Org-mode, in special contexts, these same keys are used for other
 purposes, important enough to compete with shift selection.  Org tries
 to balance these needs by supporting `shift-select-mode' outside these
@@ -278,28 +386,30 @@ is Emacs 23 only."
   :group 'org)
 
 (defcustom org-startup-folded t
-  "Non-nil means, entering Org-mode will switch to OVERVIEW.
+  "Non-nil means entering Org-mode will switch to OVERVIEW.
 This can also be configured on a per-file basis by adding one of
 the following lines anywhere in the buffer:
 
-   #+STARTUP: fold
-   #+STARTUP: nofold
-   #+STARTUP: content"
+   #+STARTUP: fold              (or `overview', this is equivalent)
+   #+STARTUP: nofold            (or `showall', this is equivalent)
+   #+STARTUP: content
+   #+STARTUP: showeverything"
   :group 'org-startup
   :type '(choice
          (const :tag "nofold: show all" nil)
          (const :tag "fold: overview" t)
-         (const :tag "content: all headlines" content)))
+         (const :tag "content: all headlines" content)
+         (const :tag "show everything, even drawers" showeverything)))
 
 (defcustom org-startup-truncated t
-  "Non-nil means, entering Org-mode will set `truncate-lines'.
+  "Non-nil means entering Org-mode will set `truncate-lines'.
 This is useful since some lines containing links can be very long and
 uninteresting.  Also tables look terrible when wrapped."
   :group 'org-startup
   :type 'boolean)
 
 (defcustom org-startup-indented nil
-  "Non-nil means, turn on `org-indent-mode' on startup.
+  "Non-nil means turn on `org-indent-mode' on startup.
 This can also be configured on a per-file basis by adding one of
 the following lines anywhere in the buffer:
 
@@ -310,8 +420,51 @@ the following lines anywhere in the buffer:
          (const :tag "Not" nil)
          (const :tag "Globally (slow on startup in large files)" t)))
 
+(defcustom org-use-sub-superscripts t
+  "Non-nil means interpret \"_\" and \"^\" for export.
+When this option is turned on, you can use TeX-like syntax for sub- and
+superscripts.  Several characters after \"_\" or \"^\" will be
+considered as a single item - so grouping with {} is normally not
+needed.  For example, the following things will be parsed as single
+sub- or superscripts.
+
+ 10^24   or   10^tau     several digits will be considered 1 item.
+ 10^-12  or   10^-tau    a leading sign with digits or a word
+ x^2-y^3                 will be read as x^2 - y^3, because items are
+                        terminated by almost any nonword/nondigit char.
+ 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.  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-startup
+  :group 'org-export-translation
+  :type '(choice
+         (const :tag "Always interpret" t)
+         (const :tag "Only with braces" {})
+         (const :tag "Never interpret" nil)))
+
+(if (fboundp 'defvaralias)
+    (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
+
+
+(defcustom org-startup-with-beamer-mode nil
+  "Non-nil means turn on `org-beamer-mode' on startup.
+This can also be configured on a per-file basis by adding one of
+the following lines anywhere in the buffer:
+
+   #+STARTUP: beamer"
+  :group 'org-startup
+  :type 'boolean)
+
 (defcustom org-startup-align-all-tables nil
-  "Non-nil means, align all tables when visiting a file.
+  "Non-nil means align all tables when visiting a file.
 This is useful when the column width in tables is forced with <N> cookies
 in table fields.  Such tables will look correct only after the first re-align.
 This can also be configured on a per-file basis by adding one of
@@ -321,6 +474,15 @@ the following lines anywhere in the buffer:
   :group 'org-startup
   :type 'boolean)
 
+(defcustom org-startup-with-inline-images nil
+  "Non-nil means show inline images when loading a new Org file.
+This can also be configured on a per-file basis by adding one of
+the following lines anywhere in the buffer:
+   #+STARTUP: inlineimages
+   #+STARTUP: noinlineimages"
+  :group 'org-startup
+  :type 'boolean)
+
 (defcustom org-insert-mode-line-in-empty-file nil
   "Non-nil means insert the first line setting Org-mode in empty files.
 When the function `org-mode' is called interactively in an empty file, this
@@ -348,10 +510,10 @@ become effective."
   :type 'boolean)
 
 (defcustom org-use-extra-keys nil
-  "Non-nil means use extra key sequence definitions for certain
-commands.  This happens automatically if you run XEmacs or if
-window-system is nil.  This variable lets you do the same
-manually.  You must set it before loading org.
+  "Non-nil means use extra key sequence definitions for certain commands.
+This happens automatically if you run XEmacs or if `window-system'
+is nil.  This variable lets you do the same manually.  You must
+set it before loading org.
 
 Example: on Carbon Emacs 22 running graphically, with an external
 keyboard on a Powerbook, the default way of setting M-left might
@@ -382,14 +544,17 @@ therefore you'll have to restart Emacs to apply it after changing."
 
 (defun 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))
+Or return the original if not disputed.
+Also apply the translations defined in `org-xemacs-key-equivalents'."
+  (when org-replace-disputed-keys
+    (let* ((nkey (key-description key))
+          (x (org-find-if (lambda (x)
+                            (equal (key-description (car x)) nkey))
+                          org-disputed-keys)))
+      (setq key (if x (cdr x) key))))
+  (when (featurep 'xemacs)
+    (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
+  key)
 
 (defun org-find-if (predicate seq)
   (catch 'exit
@@ -468,7 +633,7 @@ An entry can be toggled between QUOTE and normal with
   :type 'string)
 
 (defconst org-repeat-re
-  "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
+  "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
   "Regular expression for specifying repeated events.
 After a match, group 1 contains the repeat expression.")
 
@@ -502,7 +667,7 @@ After a match, group 1 contains the repeat expression.")
   "Contexts for the reveal options.")
 
 (defcustom org-show-hierarchy-above '((default . t))
-  "Non-nil means, show full hierarchy when revealing a location.
+  "Non-nil means show full hierarchy 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 hierarchy of headings
 above the exposed location is shown.
@@ -522,7 +687,7 @@ contexts.  Valid contexts are
   :type org-context-choice)
 
 (defcustom org-show-following-heading '((default . nil))
-  "Non-nil means, show following heading when revealing a location.
+  "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
 match is shown.
@@ -535,7 +700,7 @@ contexts.  See `org-show-hierarchy-above' for valid contexts."
   :type org-context-choice)
 
 (defcustom org-show-siblings '((default . nil) (isearch t))
-  "Non-nil means, show all sibling heading when revealing a location.
+  "Non-nil means show all sibling 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 sibling of the current entry
 heading are all made visible.  If `org-show-hierarchy-above' is t,
@@ -551,7 +716,7 @@ contexts.  See `org-show-hierarchy-above' for valid contexts."
   :type org-context-choice)
 
 (defcustom org-show-entry-below '((default . nil))
-  "Non-nil means, show the entry below a headline when revealing a location.
+  "Non-nil means show the entry below a headline 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 text below the headline that is
 exposed is also shown.
@@ -581,13 +746,45 @@ new-frame        Make a new frame each time.  Note that in this case
          (const :tag "Each time a new frame" new-frame)
          (const :tag "One dedicated frame" dedicated-frame)))
 
+(defcustom org-use-speed-commands nil
+  "Non-nil means activate single letter commands at beginning of a headline.
+This may also be a function to test for appropriate locations where speed
+commands should be active."
+  :group 'org-structure
+  :type '(choice
+         (const :tag "Never" nil)
+         (const :tag "At beginning of headline stars" t)
+         (function)))
+
+(defcustom org-speed-commands-user nil
+    "Alist of additional speed commands.
+This list will be checked before `org-speed-commands-default'
+when the variable `org-use-speed-commands' is non-nil
+and when the cursor is at the beginning of a headline.
+The car if each entry is a string with a single letter, which must
+be assigned to `self-insert-command' in the global map.
+The cdr is either a command to be called interactively, a function
+to be called, or a form to be evaluated.
+An entry that is just a list with a single string will be interpreted
+as a descriptive headline that will be added when listing the speed
+commands in the Help buffer using the `?' speed command."
+    :group 'org-structure
+    :type '(repeat :value ("k" . ignore)
+           (choice :value ("k" . ignore)
+            (list :tag "Descriptive Headline" (string :tag "Headline"))
+            (cons :tag "Letter and Command"
+             (string :tag "Command letter")
+             (choice
+              (function)
+              (sexp))))))
+
 (defgroup org-cycle nil
   "Options concerning visibility cycling in Org-mode."
   :tag "Org Cycle"
   :group 'org-structure)
 
 (defcustom org-cycle-skip-children-state-if-no-children t
-  "Non-nil means, skip CHILDREN state in entries that don't have any."
+  "Non-nil means skip CHILDREN state in entries that don't have any."
   :group 'org-cycle
   :type 'boolean)
 
@@ -624,7 +821,7 @@ Drawers can be defined on the per-file basis with a line like:
   :type '(repeat (string :tag "Drawer Name")))
 
 (defcustom org-hide-block-startup nil
-  "Non-nil means, , entering Org-mode will fold all blocks.
+  "Non-nil means entering Org-mode will fold all blocks.
 This can also be set in on a per-file basis with
 
 #+STARTUP: hideblocks
@@ -636,7 +833,8 @@ This can also be set in on a per-file basis with
 (defcustom org-cycle-global-at-bob nil
   "Cycle globally if cursor is at beginning of buffer and not at a headline.
 This makes it possible to do global cycling without having to use S-TAB or
-C-u TAB.  For this special case to work, the first line of the buffer
+\\[universal-argument] TAB.  For this special case to work, the first line \
+of the buffer
 must not be a headline - it may be empty or some other text.  When used in
 this way, `org-cycle-hook' is disables temporarily, to make sure the
 cursor stays at the beginning of the buffer.
@@ -645,6 +843,21 @@ of the buffer."
   :group 'org-cycle
   :type 'boolean)
 
+(defcustom org-cycle-level-after-item/entry-creation t
+  "Non-nil means cycle entry level or item indentation in new empty entries.
+
+When the cursor is at the end of an empty headline, i.e with only stars
+and maybe a TODO keyword, TAB will then switch the entry to become a child,
+and then all possible ancestor states, before returning to the original state.
+This makes data entry extremely fast:  M-RET to create a new headline,
+on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
+
+When the cursor is at the end of an empty plain list item, one TAB will
+make it a subitem, two or more tabs will back up to make this an item
+higher up in the item hierarchy."
+  :group 'org-cycle
+  :type 'boolean)
+
 (defcustom org-cycle-emulate-tab t
   "Where should `org-cycle' emulate TAB.
 nil         Never
@@ -668,7 +881,7 @@ 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
+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.
 
@@ -709,7 +922,7 @@ the values `folded', `children', or `subtree'."
   :group 'org-structure)
 
 (defcustom org-odd-levels-only nil
-  "Non-nil means, skip even levels and only use odd levels for the outline.
+  "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
 promotion/demotion commands.  It also influences how levels are
 handled by the exporters.
@@ -721,11 +934,11 @@ lines to the buffer:
    #+STARTUP: odd
    #+STARTUP: oddeven"
   :group 'org-edit-structure
-  :group 'org-font-lock
+  :group 'org-appearance
   :type 'boolean)
 
 (defcustom org-adapt-indentation t
-  "Non-nil means, adapt indentation to outline node level.
+  "Non-nil means adapt indentation to outline node level.
 
 When this variable is set, Org assumes that you write outlines by
 indenting text in each node to align with the headline (after the stars).
@@ -759,7 +972,9 @@ it to the beginning of the line.
 
 `C-e' will jump to the end of the headline, ignoring the presence of tags
 in the headline.  A second `C-e' will then jump to the true end of the
-line, after any tags.
+line, after any tags.  This also means that, when this variable is
+non-nil, `C-e' also will never jump beyond the end of the heading of a
+folded section, i.e. not after the ellipses.
 
 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
 going to the true line boundary first.  Only a directly following, identical
@@ -770,17 +985,17 @@ set separately."
   :group 'org-edit-structure
   :type '(choice
          (const :tag "off" nil)
-         (const :tag "after stars/bullet and before tags first" t)
-         (const :tag "true line boundary first" reversed)
+         (const :tag "on: after stars/bullet and before tags first" t)
+         (const :tag "reversed: true line boundary first" reversed)
          (cons :tag "Set C-a and C-e separately"
                (choice :tag "Special C-a"
                        (const :tag "off" nil)
-                       (const :tag "after  stars/bullet first" t)
-                       (const :tag "before stars/bullet first" reversed))
+                       (const :tag "on: after  stars/bullet first" t)
+                       (const :tag "reversed: before stars/bullet first" reversed))
                (choice :tag "Special C-e"
                        (const :tag "off" nil)
-                       (const :tag "before tags first" t)
-                       (const :tag "after tags first" reversed)))))
+                       (const :tag "on: before tags first" t)
+                       (const :tag "reversed: after tags first" reversed)))))
 (if (fboundp 'defvaralias)
     (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
 
@@ -796,8 +1011,20 @@ When t, the following will happen while the cursor is in the headline:
   :group 'org-edit-structure
   :type 'boolean)
 
+(defcustom org-ctrl-k-protect-subtree nil
+  "Non-nil means, do not delete a hidden subtree with C-k.
+When set to the symbol `error', simply throw an error when C-k is
+used to kill (part-of) a headline that has hidden text behind it.
+Any other non-nil value will result in a query to the user, if it is
+OK to kill that hidden subtree.  When nil, kill without remorse."
+  :group 'org-edit-structure
+  :type '(choice
+         (const :tag "Do not protect hidden subtrees" nil)
+         (const :tag "Protect hidden subtrees with a security query" t)
+         (const :tag "Never kill a hidden subtree with C-k" error)))
+
 (defcustom org-yank-folded-subtrees t
-  "Non-nil means, when yanking subtrees, fold them.
+  "Non-nil means when yanking subtrees, fold them.
 If the kill is a single subtree, or a sequence of subtrees, i.e. if
 it starts with a heading and all other headings in it are either children
 or siblings, then fold all the subtrees.  However, do this only if no
@@ -806,14 +1033,14 @@ text after the yank would be swallowed into a folded tree by this action."
   :type 'boolean)
 
 (defcustom org-yank-adjusted-subtrees nil
-  "Non-nil means, when yanking subtrees, adjust the level.
+  "Non-nil means when yanking subtrees, adjust the level.
 With this setting, `org-paste-subtree' is used to insert the subtree, see
 this function for details."
   :group 'org-edit-structure
   :type 'boolean)
 
 (defcustom org-M-RET-may-split-line '((default . t))
-  "Non-nil means, M-RET will split the line at the cursor position.
+  "Non-nil means M-RET will split the line at the cursor position.
 When nil, it will go to the end of the line before making a
 new line.
 You may also set this option in a different way for different
@@ -840,7 +1067,7 @@ default   the value to be used for all contexts not explicitly
 
 
 (defcustom org-insert-heading-respect-content nil
-  "Non-nil means, insert new headings after the current subtree.
+  "Non-nil means insert new headings after the current subtree.
 When nil, the new heading is created directly after the current line.
 The commands \\[org-insert-heading-respect-content] and
 \\[org-insert-todo-heading-respect-content] turn this variable on
@@ -852,9 +1079,13 @@ for the duration of the command."
                                        (plain-list-item . auto))
   "Should `org-insert-heading' leave a blank line before new heading/item?
 The value is an alist, with `heading' and `plain-list-item' as car,
-and a boolean flag as cdr.  For plain lists, if the variable
-`org-empty-line-terminates-plain-lists' is set, the setting here
-is ignored and no empty line is inserted, to keep the list in tact."
+and a boolean flag as cdr. The cdr may lso be the symbol `auto', and then
+Org will look at the surrounding headings/items and try to make an
+intelligent decision wether to insert a blank line or not.
+
+For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
+set, the setting here is ignored and no empty line is inserted, to avoid
+breaking the list structure."
   :group 'org-edit-structure
   :type '(list
          (cons (const heading)
@@ -872,16 +1103,15 @@ is ignored and no empty line is inserted, to keep the list in tact."
   :type 'hook)
 
 (defcustom org-enable-fixed-width-editor t
-  "Non-nil means, lines starting with \":\" are treated as fixed-width.
-This currently only means, they are never auto-wrapped.
+  "Non-nil means lines starting with \":\" are treated as fixed-width.
+This currently only means they are never auto-wrapped.
 When nil, such lines will be treated like ordinary lines.
 See also the QUOTE keyword."
   :group 'org-edit-structure
   :type 'boolean)
 
-
 (defcustom org-goto-auto-isearch t
-  "Non-nil means, typing characters in org-goto starts incremental search."
+  "Non-nil means typing characters in `org-goto' starts incremental search."
   :group 'org-edit-structure
   :type 'boolean)
 
@@ -891,14 +1121,14 @@ See also the QUOTE keyword."
   :group 'org-structure)
 
 (defcustom org-highlight-sparse-tree-matches t
-  "Non-nil means, highlight all matches that define a sparse tree.
+  "Non-nil means highlight all matches that define a sparse tree.
 The highlights will automatically disappear the next time the buffer is
 changed by an edit command."
   :group 'org-sparse-trees
   :type 'boolean)
 
 (defcustom org-remove-highlights-with-change t
-  "Non-nil means, any change to the buffer will remove temporary highlights.
+  "Non-nil means any change to the buffer will remove temporary highlights.
 Such highlights are created by `org-occur' and `org-clock-display'.
 When nil, `C-c C-c needs to be used to get rid of the highlights.
 The highlights created by `org-preview-latex-fragment' always need
@@ -932,7 +1162,7 @@ This also applied for speedbar access."
   :group 'org)
 
 (defcustom org-enable-table-editor 'optimized
-  "Non-nil means, lines starting with \"|\" are handled by the table editor.
+  "Non-nil means lines starting with \"|\" are handled by the table editor.
 When nil, such lines will be treated like ordinary lines.
 
 When equal to the symbol `optimized', the table editor will be optimized to
@@ -964,14 +1194,14 @@ See also the variable `org-table-auto-blank-field'."
 
 (defcustom org-self-insert-cluster-for-undo t
   "Non-nil means cluster self-insert commands for undo when possible.
-If this is set, then, like in the Emacs command loop, 20 consequtive
+If this is set, then, like in the Emacs command loop, 20 consecutive
 characters will be undone together.
 This is configurable, because there is some impact on typing performance."
   :group 'org-table
   :type 'boolean)
 
 (defcustom org-table-tab-recognizes-table.el t
-  "Non-nil means, TAB will automatically notice a table.el table.
+  "Non-nil means TAB will automatically notice a table.el table.
 When it sees such a table, it moves point into it and - if necessary -
 calls `table-recognize-table'."
   :group 'org-table-editing
@@ -1016,7 +1246,7 @@ See the manual for examples."
            (function)))))
 
 (defcustom org-descriptive-links t
-  "Non-nil means, hide link part and only show description of bracket links.
+  "Non-nil means hide link part and only show description of bracket links.
 Bracket links are like [[link][description]].  This variable sets the initial
 state in new org-mode buffers.  The setting can then be toggled on a
 per-buffer basis from the Org->Hyperlinks menu."
@@ -1047,7 +1277,7 @@ type.  In principle, it does not hurt to turn on most link types - there may
 be a small gain when turning off unused link types.  The types are:
 
 bracket   The recommended [[link][description]] or [[link]] links with hiding.
-angular   Links in angular brackets that may contain whitespace like
+angle     Links in angular brackets that may contain whitespace like
           <bbdb:Carsten Dominik>.
 plain     Plain links in normal text, no whitespace, like http://google.com.
 radio     Text that is matched by a radio target, see manual for details.
@@ -1058,8 +1288,8 @@ footnote  Footnote labels.
 Changing this variable requires a restart of Emacs to become effective."
   :group 'org-link
   :type '(set :greedy t
-             (const :tag "Double bracket links (new style)" bracket)
-             (const :tag "Angular bracket links (old style)" angular)
+             (const :tag "Double bracket links" bracket)
+             (const :tag "Angular bracket links" angle)
              (const :tag "Plain text links" plain)
              (const :tag "Radio target matches" radio)
              (const :tag "Tags" tag)
@@ -1067,11 +1297,11 @@ Changing this variable requires a restart of Emacs to become effective."
              (const :tag "Footnotes" footnote)))
 
 (defcustom org-make-link-description-function nil
-  "Function to use to generate link descriptions from links. If
-nil the link location will be used. This function must take two
-parameters; the first is the link and the second the description
-org-insert-link has generated, and should return the description
-to use."
+  "Function to use to generate link descriptions from links.
+If nil the link location will be used.  This function must take
+two parameters; the first is the link and the second the
+description `org-insert-link' has generated, and should return the
+description to use."
   :group 'org-link
   :type 'function)
 
@@ -1113,7 +1343,7 @@ It should match if the message is from the user him/herself."
   :type 'regexp)
 
 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
-  "Non-nil means, storing a link to an Org file will use entry IDs.
+  "Non-nil means storing a link to an Org file will use entry IDs.
 
 Note that before this variable is even considered, org-id must be loaded,
 so please customize `org-modules' and turn it on.
@@ -1153,17 +1383,20 @@ nil   Never use an ID to make a link, instead link using a text search for
          (const :tag "Do not use ID to create link" nil)))
 
 (defcustom org-context-in-file-links t
-  "Non-nil means, file links from `org-store-link' contain context.
+  "Non-nil means file links from `org-store-link' contain context.
 A search string will be added to the file name with :: as separator and
-used to find the context when the link is activated by the command
-`org-open-at-point'.
+used to find the context when the link is activated by the command 
+`org-open-at-point'. When this option is t, the entire active region 
+will be placed in the search string of the file link. If set to a 
+positive integer, only the first n lines of context will be stored.
+
 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
 negates this setting for the duration of the command."
   :group 'org-link-store
-  :type 'boolean)
+  :type '(choice boolean integer))
 
 (defcustom org-keep-stored-link-after-insertion nil
-  "Non-nil means, keep link in list for entire session.
+  "Non-nil means keep link in list for entire session.
 
 The command `org-store-link' adds a link pointing to the current
 location to an internal list.  These links accumulate during a session.
@@ -1200,7 +1433,7 @@ links created by planner."
   :type 'hook)
 
 (defcustom org-tab-follows-link nil
-  "Non-nil means, on links TAB will follow the link.
+  "Non-nil means on links TAB will follow the link.
 Needs to be set before org.el is loaded.
 This really should not be used, it does not make sense, and the
 implementation is bad."
@@ -1208,29 +1441,40 @@ implementation is bad."
   :type 'boolean)
 
 (defcustom org-return-follows-link nil
-  "Non-nil means, on links RET will follow the link.
-Needs to be set before org.el is loaded."
+  "Non-nil means on links RET will follow the link."
   :group 'org-link-follow
   :type 'boolean)
 
 (defcustom org-mouse-1-follows-link
   (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
-  "Non-nil means, mouse-1 on a link will follow the link.
+  "Non-nil means mouse-1 on a link will follow the link.
 A longer mouse click will still set point.  Does not work on XEmacs.
 Needs to be set before org.el is loaded."
   :group 'org-link-follow
   :type 'boolean)
 
 (defcustom org-mark-ring-length 4
-  "Number of different positions to be recorded in the ring
+  "Number of different positions to be recorded in the ring.
 Changing this requires a restart of Emacs to work correctly."
   :group 'org-link-follow
   :type 'integer)
 
+(defcustom org-link-search-must-match-exact-headline 'query-to-create
+  "Non-nil means internal links in Org files must exactly match a headline.
+When nil, the link search tries to match a phrase will all words
+in the search text."
+  :group 'org-link-follow
+  :type '(choice
+         (const :tag "Use fuzy text search" nil)
+         (const :tag "Match only exact headline" t)
+         (const :tag "Match extact headline or query to create it"
+                query-to-create)))
+
 (defcustom org-link-frame-setup
   '((vm . vm-visit-folder-other-frame)
-    (gnus . gnus-other-frame)
-    (file . find-file-other-window))
+    (gnus . org-gnus-no-new-news)
+    (file . find-file-other-window)
+    (wl . wl-other-frame))
   "Setup the frame configuration for following links.
 When following a link with Emacs, it may often be useful to display
 this link in another window or frame.  This variable can be used to
@@ -1246,6 +1490,9 @@ For FILE, use any of
     `find-file'
     `find-file-other-window'
     `find-file-other-frame'
+For Wanderlust use any of
+    `wl'
+    `wl-other-frame'
 For the calendar, use the variable `calendar-setup'.
 For BBDB, it is currently only possible to display the matches in
 another window."
@@ -1265,13 +1512,18 @@ another window."
                (choice
                 (const find-file)
                 (const find-file-other-window)
-                (const find-file-other-frame)))))
+                (const find-file-other-frame)))
+         (cons (const wl)
+               (choice
+                (const wl)
+                (const wl-other-frame)))))
 
 (defcustom org-display-internal-link-with-indirect-buffer nil
-  "Non-nil means, use indirect buffer to display infile links.
+  "Non-nil means use indirect buffer to display infile links.
 Activating internal links (from one location in a file to another location
 in the same file) normally just jumps to the location.  When the link is
-activated with a C-u prefix (or with mouse-3), the link is displayed in
+activated with a \\[universal-argument] prefix (or with mouse-3), the link \
+is displayed in
 another window.  When this option is set, the other window actually displays
 an indirect buffer clone of the current buffer, to avoid any visibility
 changes to the current buffer."
@@ -1279,16 +1531,16 @@ changes to the current buffer."
   :type 'boolean)
 
 (defcustom org-open-non-existing-files nil
-  "Non-nil means, `org-open-file' will open non-existing files.
+  "Non-nil means `org-open-file' will open non-existing files.
 When nil, an error will be generated.
 This variable applies only to external applications because they
 might choke on non-existing files.  If the link is to a file that
-will be openend in Emacs, the variable is ignored."
+will be opened in Emacs, the variable is ignored."
   :group 'org-link-follow
   :type 'boolean)
 
 (defcustom org-open-directory-means-index-dot-org nil
-  "Non-nil means, a link to a directory really means to index.org.
+  "Non-nil means a link to a directory really means to index.org.
 When nil, following a directory link will run dired or open a finder/explorer
 window on that directory."
   :group 'org-link-follow
@@ -1296,7 +1548,7 @@ window on that directory."
 
 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
   "Function and arguments to call for following mailto links.
-This is a list with the first element being a lisp function, and the
+This is a list with the first element being a Lisp function, and the
 remaining elements being arguments to the function.  In string arguments,
 %a will be replaced by the address, and %s will be replaced by the subject
 if one was given like in <mailto:arthur@galaxy.org::this subject>."
@@ -1308,7 +1560,7 @@ if one was given like in <mailto:arthur@galaxy.org::this subject>."
          (cons :tag "other" (function) (repeat :tag "argument" sexp))))
 
 (defcustom org-confirm-shell-link-function 'yes-or-no-p
-  "Non-nil means, ask for confirmation before executing shell links.
+  "Non-nil means ask for confirmation before executing shell links.
 Shell links can be dangerous: just think about a link
 
      [[shell:rm -rf ~/*][Google Search]]
@@ -1323,9 +1575,12 @@ single keystroke rather than having to type \"yes\"."
          (const :tag "with yes-or-no (safer)" yes-or-no-p)
          (const :tag "with y-or-n (faster)" y-or-n-p)
          (const :tag "no confirmation (dangerous)" nil)))
+(put 'org-confirm-shell-link-function
+     'safe-local-variable
+     '(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
 
 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
-  "Non-nil means, ask for confirmation before executing Emacs Lisp links.
+  "Non-nil means ask for confirmation before executing Emacs Lisp links.
 Elisp links can be dangerous: just think about a link
 
      [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
@@ -1340,6 +1595,9 @@ single keystroke rather than having to type \"yes\"."
          (const :tag "with yes-or-no (safer)" yes-or-no-p)
          (const :tag "with y-or-n (faster)" y-or-n-p)
          (const :tag "no confirmation (dangerous)" nil)))
+(put 'org-confirm-shell-link-function
+     'safe-local-variable
+     '(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
 
 (defconst org-file-apps-defaults-gnu
   '((remote . emacs)
@@ -1381,6 +1639,7 @@ See `org-file-apps'.")
 (defcustom org-file-apps
   '(
     (auto-mode . emacs)
+    ("\\.mm\\'" . default)
     ("\\.x?html?\\'" . default)
     ("\\.pdf\\'" . default)
     )
@@ -1390,9 +1649,37 @@ you can use this variable to set the application for a given file
 extension.  The entries in this list are cons cells where the car identifies
 files and the cdr the corresponding command.  Possible values for the
 file identifier are
- \"regex\"     Regular expression matched against the file name.  For backward
-               compatibility, this can also be a string with only alphanumeric
-               characters, which is then interpreted as an extension.
+ \"string\"    A string as a file identifier can be interpreted in different
+               ways, depending on its contents:
+
+               - Alphanumeric characters only:
+                 Match links with this file extension.
+                 Example: (\"pdf\" . \"evince %s\")
+                          to open PDFs with evince.
+
+               - Regular expression: Match links where the
+                 filename matches the regexp.  If you want to
+                 use groups here, use shy groups.
+
+                 Example: (\"\\.x?html\\'\" . \"firefox %s\")
+                          (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
+                          to open *.html and *.xhtml with firefox.
+
+               - Regular expression which contains (non-shy) groups:
+                 Match links where the whole link, including \"::\", and
+                 anything after that, matches the regexp.
+                 In a custom command string, %1, %2, etc. are replaced with
+                 the parts of the link that were matched by the groups.
+                 For backwards compatibility, if a command string is given
+                 that does not use any of the group matches, this case is
+                 handled identically to the second one (i.e. match against
+                 file name only).
+                 In a custom lisp form, you can access the group matches with
+                 (match-string n link).
+
+                 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
+                     to open [[file:document.pdf::5]] with evince at page 5.
+
  `directory'   Matches a directory
  `remote'      Matches a remote file, accessible through tramp or efs.
                Remote files most likely should be visited through Emacs
@@ -1406,7 +1693,7 @@ file identifier are
  `system'      The system command to open files, like `open' on Windows
                and Mac OS X, and mailcap under GNU/Linux.  This is the command
                that will be selected if you call `C-c C-o' with a double
-               `C-u C-u' prefix.
+               \\[universal-argument] \\[universal-argument] prefix.
 
 Possible values for the command are:
  `emacs'       The file will be visited by the current Emacs process.
@@ -1445,6 +1732,8 @@ For more examples, see the system specific constants
                        (string :tag "Command")
                        (sexp :tag "Lisp form")))))
 
+
+
 (defgroup org-refile nil
   "Options concerning refiling entries in Org-mode."
   :tag "Org Refile"
@@ -1460,7 +1749,7 @@ following situations:
    absolute path.  The path will then be interpreted relative to
    `org-directory'
 2. When a remember note is filed away in an interactive way (when exiting the
-   note buffer with `C-1 C-c C-c'.  The the user is prompted for an org file,
+   note buffer with `C-1 C-c C-c'.  The user is prompted for an org file,
    with `org-directory' as the default path."
   :group 'org-refile
   :group 'org-remember
@@ -1468,10 +1757,8 @@ following situations:
 
 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
   "Default target for storing notes.
-Used by the hooks for remember.el.  This can be a string, or nil to mean
-the value of `remember-data-file'.
-You can set this on a per-template basis with the variable
-`org-remember-templates'."
+Used as a fall back file for org-remember.el and org-capture.el, for
+templates that do not specify a target file."
   :group 'org-refile
   :group 'org-remember
   :type '(choice
@@ -1493,12 +1780,12 @@ outline-path-completion  Headlines in the current buffer are offered via
          (const :tag "Outline-path-completion" outline-path-completion)))
 
 (defcustom org-goto-max-level 5
-  "Maximum level to be considered when running org-goto with refile interface."
+  "Maximum target level when running `org-goto' with refile interface."
   :group 'org-refile
   :type 'integer)
 
 (defcustom org-reverse-note-order nil
-  "Non-nil means, store new notes at the beginning of a file or entry.
+  "Non-nil means store new notes at the beginning of a file or entry.
 When nil, new notes will be filed to the end of a file or entry.
 This can also be a list with cons cells of regular expressions that
 are matched against file names, and values."
@@ -1510,13 +1797,40 @@ are matched against file names, and values."
          (repeat :tag "By file name regexp"
                  (cons regexp boolean))))
 
+(defcustom org-log-refile nil
+  "Information to record when a task is refiled.
+
+Possible values are:
+
+nil     Don't add anything
+time    Add a time stamp to the task
+note    Prompt for a note and add it with template `org-log-note-headings'
+
+This option can also be set with on a per-file-basis with
+
+   #+STARTUP: nologrefile
+   #+STARTUP: logrefile
+   #+STARTUP: lognoterefile
+
+You can have local logging settings for a subtree by setting the LOGGING
+property to one or more of these keywords.
+
+When bulk-refiling from the agenda, the value `note' is forbidden and
+will temporarily be changed to `time'."
+  :group 'org-refile
+  :group 'org-progress
+  :type '(choice
+         (const :tag "No logging" nil)
+         (const :tag "Record timestamp" time)
+         (const :tag "Record timestamp with note." note)))
+
 (defcustom org-refile-targets nil
   "Targets for refiling entries with \\[org-refile].
 This is list of cons cells.  Each cell contains:
 - a specification of the files to be considered, either a list of files,
   or a symbol whose function or variable value will be used to retrieve
   a file name or a list of file names.  If you use `org-agenda-files' for
-  that, all agenda files will be scanned for targets.  Nil means, consider
+  that, all agenda files will be scanned for targets.  Nil means consider
   headings in the current buffer.
 - A specification of how to find candidate refile targets.  This may be
   any of:
@@ -1535,7 +1849,7 @@ This is list of cons cells.  Each cell contains:
     order in hierarchy, not to the number of stars.
 
 You can set the variable `org-refile-target-verify-function' to a function
-to verify each headline found by the simple critery above.
+to verify each headline found by the simple criteria above.
 
 When this variable is nil, all top-level headlines in the current buffer
 are used, equivalent to the value `((nil . (:level . 1))'."
@@ -1567,8 +1881,19 @@ of the subtree."
   :group 'org-refile
   :type 'function)
 
+(defcustom org-refile-use-cache nil
+  "Non-nil means cache refile targets to speed up the process.
+The cache for a particular file will be updated automatically when
+the buffer has been killed, or when any of the marker used for flagging
+refile targets no longer points at a live buffer.
+If you have added new entries to a buffer that might themselves be targets,
+you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
+find that easier, `C-u C-u C-u C-c C-w'."
+  :group 'org-refile
+  :type 'boolean)
+
 (defcustom org-refile-use-outline-path nil
-  "Non-nil means, provide refile targets as paths.
+  "Non-nil means provide refile targets as paths.
 So a level 3 headline will be available as level1/level2/level3.
 
 When the value is `file', also include the file name (without directory)
@@ -1584,7 +1909,7 @@ the file name, to get entries inserted as top level in the file.
          (const :tag "Start with full file path" full-file-path)))
 
 (defcustom org-outline-path-complete-in-steps t
-  "Non-nil means, complete the outline path in hierarchical steps.
+  "Non-nil means complete the outline path in hierarchical steps.
 When Org-mode uses the refile interface to select an outline path
 \(see variable `org-refile-use-outline-path'), the completion of
 the path can be done is a single go, or if can be done in steps down
@@ -1596,7 +1921,7 @@ fast, while still showing the whole path to the entry."
   :type 'boolean)
 
 (defcustom org-refile-allow-creating-parent-nodes nil
-  "Non-nil means, allow to create new nodes as refile targets.
+  "Non-nil means allow to create new nodes as refile targets.
 New nodes are then created by adding \"/new node name\" to the completion
 of an existing node.  When the value of this variable is `confirm',
 new node creation must be confirmed by the user (recommended)
@@ -1626,9 +1951,8 @@ heading."
   '(
     (:tag "Sequence (cycling hits every state)" sequence)
     (:tag "Type     (cycling directly to DONE)" type))
-  "The available interpretation symbols for customizing
- `org-todo-keywords'.
- Interested libraries should add to this list.")
+  "The available interpretation symbols for customizing `org-todo-keywords'.
+Interested libraries should add to this list.")
 
 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
   "List of TODO entry keyword sequences and their interpretation.
@@ -1639,7 +1963,7 @@ 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
+the \"keywords\" is the vertical bar, \"|\", 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.
 
@@ -1654,7 +1978,7 @@ Each keyword can optionally specify a character for fast state selection
 \(in combination with the variable `org-use-fast-todo-selection')
 and specifiers for state change logging, using the same syntax
 that is used in the \"#+TODO:\" lines.  For example, \"WAIT(w)\" says
-that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
+that the WAIT state can be selected with the \"w\" key.  \"WAIT(w!)\"
 indicates to record a time stamp each time this state is selected.
 
 Each keyword may also specify if a timestamp or a note should be
@@ -1699,6 +2023,7 @@ taken from the (otherwise obsolete) variable `org-todo-interpretation'."
 (make-variable-buffer-local 'org-todo-keywords-1)
 (defvar org-todo-keywords-for-agenda nil)
 (defvar org-done-keywords-for-agenda nil)
+(defvar org-drawers-for-agenda nil)
 (defvar org-todo-keyword-alist-for-agenda nil)
 (defvar org-tag-alist-for-agenda nil)
 (defvar org-agenda-contributing-files nil)
@@ -1731,7 +2056,7 @@ more information."
                 (const type)))
 
 (defcustom org-use-fast-todo-selection t
-  "Non-nil means, use the fast todo selection scheme with C-c C-t.
+  "Non-nil means use the fast todo selection scheme with C-c C-t.
 This variable describes if and under what circumstances the cycling
 mechanism for TODO keywords will be replaced by a single-key, direct
 selection scheme.
@@ -1755,7 +2080,7 @@ by a letter in parenthesis, like TODO(t)."
          (const :tag "Only with C-u C-c C-t" prefix)))
 
 (defcustom org-provide-todo-statistics t
-  "Non-nil means, update todo statistics after insert and toggle.
+  "Non-nil means update todo statistics after insert and toggle.
 ALL-HEADLINES means update todo statistics by including headlines
 with no TODO keyword as well, counting them as not done.
 A list of TODO keywords means the same, but skip keywords that are
@@ -1772,7 +2097,7 @@ current entry each time a todo state is changed."
          (other :tag "No TODO statistics" nil)))
 
 (defcustom org-hierarchical-todo-statistics t
-  "Non-nil means, TODO statistics covers just direct children.
+  "Non-nil means TODO statistics covers just direct children.
 When nil, all entries in the subtree are considered.
 This has only an effect if `org-provide-todo-statistics' is set.
 To set this to nil for only a single subtree, use a COOKIE_DATA
@@ -1817,7 +2142,7 @@ TODO state changes
 :to    new state, like in :from")
 
 (defcustom org-enforce-todo-dependencies nil
-  "Non-nil means, undone TODO entries will block switching the parent to DONE.
+  "Non-nil means undone TODO entries will block switching the parent to DONE.
 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
 be blocked if any prior sibling is not yet done.
 Finally, if the parent is blocked because of ordered siblings of its own,
@@ -1836,7 +2161,7 @@ to change is while Emacs is running is through the customize interface."
   :type 'boolean)
 
 (defcustom org-enforce-todo-checkbox-dependencies nil
-  "Non-nil means, unchecked boxes will block switching the parent to DONE.
+  "Non-nil means unchecked boxes will block switching the parent to DONE.
 When this is nil, checkboxes have no influence on switching TODO states.
 When non-nil, you first need to check off all check boxes before the TODO
 entry can be switched to DONE.
@@ -1854,7 +2179,7 @@ to change is while Emacs is running is through the customize interface."
   :type 'boolean)
 
 (defcustom org-treat-insert-todo-heading-as-state-change nil
-  "Non-nil means, inserting a TODO heading is treated as state change.
+  "Non-nil means inserting a TODO heading is treated as state change.
 So when the command \\[org-insert-todo-heading] is used, state change
 logging will apply if appropriate.  When nil, the new TODO item will
 be inserted directly, and no logging will take place."
@@ -1862,7 +2187,7 @@ be inserted directly, and no logging will take place."
   :type 'boolean)
 
 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
-  "Non-nil means, switching TODO states with S-cursor counts as state change.
+  "Non-nil means switching TODO states with S-cursor counts as state change.
 This is the default behavior.  However, setting this to nil allows a
 convenient way to select a TODO state and bypass any logging associated
 with that."
@@ -1897,7 +2222,7 @@ Possible values are:
 
 nil     Don't add anything, just change the keyword
 time    Add a time stamp to the task
-note    Prompt a closing note and add it with template `org-log-note-headings'
+note    Prompt for a note and add it with template `org-log-note-headings'
 
 This option can also be set with on a per-file-basis with
 
@@ -1912,7 +2237,7 @@ property to one or more of these keywords."
   :type '(choice
          (const :tag "No logging" nil)
          (const :tag "Record CLOSED timestamp" time)
-         (const :tag "Record CLOSED timestamp with closing note." note)))
+         (const :tag "Record CLOSED timestamp with note." note)))
 
 ;; Normalize old uses of org-log-done.
 (cond
@@ -1920,8 +2245,53 @@ property to one or more of these keywords."
  ((and (listp org-log-done) (memq 'done org-log-done))
   (setq org-log-done 'note)))
 
+(defcustom org-log-reschedule nil
+  "Information to record when the scheduling date of a tasks is modified.
+
+Possible values are:
+
+nil     Don't add anything, just change the date
+time    Add a time stamp to the task
+note    Prompt for a note and add it with template `org-log-note-headings'
+
+This option can also be set with on a per-file-basis with
+
+   #+STARTUP: nologreschedule
+   #+STARTUP: logreschedule
+   #+STARTUP: lognotereschedule"
+  :group 'org-todo
+  :group 'org-progress
+  :type '(choice
+         (const :tag "No logging" nil)
+         (const :tag "Record timestamp" time)
+         (const :tag "Record timestamp with note." note)))
+
+(defcustom org-log-redeadline nil
+  "Information to record when the deadline date of a tasks is modified.
+
+Possible values are:
+
+nil     Don't add anything, just change the date
+time    Add a time stamp to the task
+note    Prompt for a note and add it with template `org-log-note-headings'
+
+This option can also be set with on a per-file-basis with
+
+   #+STARTUP: nologredeadline
+   #+STARTUP: logredeadline
+   #+STARTUP: lognoteredeadline
+
+You can have local logging settings for a subtree by setting the LOGGING
+property to one or more of these keywords."
+  :group 'org-todo
+  :group 'org-progress
+  :type '(choice
+         (const :tag "No logging" nil)
+         (const :tag "Record timestamp" time)
+         (const :tag "Record timestamp with note." note)))
+
 (defcustom org-log-note-clock-out nil
-  "Non-nil means, record a note when clocking out of an item.
+  "Non-nil means record a note when clocking out of an item.
 This can also be configured on a per-file basis by adding one of
 the following lines anywhere in the buffer:
 
@@ -1932,7 +2302,7 @@ the following lines anywhere in the buffer:
   :type 'boolean)
 
 (defcustom org-log-done-with-time t
-  "Non-nil means, the CLOSED time stamp will contain date and time.
+  "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)
@@ -1941,16 +2311,25 @@ When nil, only the date will be recorded."
   '((done .  "CLOSING NOTE %t")
     (state . "State %-12s from %-12S %t")
     (note .  "Note taken on %t")
+    (reschedule .  "Rescheduled from %S on %t")
+    (delschedule .  "Not scheduled, was %S on %t")
+    (redeadline .  "New deadline from %S on %t")
+    (deldeadline .  "Removed deadline, was %S on %t")
+    (refile . "Refiled on %t")
     (clock-out . ""))
   "Headings for notes added to entries.
 The value is an alist, with the car being a symbol indicating the note
 context, and the cdr is the heading to be used.  The heading may also be the
 empty string.
 %t in the heading will be replaced by a time stamp.
+%T will be an active time stamp instead the default inactive one
 %s will be replaced by the new TODO state, in double quotes.
 %S will be replaced by the old TODO state, in double quotes.
 %u will be replaced by the user name.
-%U will be replaced by the full user name."
+%U will be replaced by the full user name.
+
+In fact, it is not a good idea to change the `state' entry, because
+agenda log mode depends on the format of these entries."
   :group  'org-todo
   :group  'org-progress
   :type '(list :greedy t
@@ -1959,13 +2338,18 @@ empty string.
                       "Heading when changing todo state (todo sequence only)"
                       state) string)
          (cons (const :tag "Heading when just taking a note" note) string)
-         (cons (const :tag "Heading when clocking out" clock-out) string)))
+         (cons (const :tag "Heading when clocking out" clock-out) string)
+         (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
+         (cons (const :tag "Heading when rescheduling" reschedule) string)
+         (cons (const :tag "Heading when changing deadline"  redeadline) string)
+         (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
+         (cons (const :tag "Heading when refiling" refile) string)))
 
 (unless (assq 'note org-log-note-headings)
   (push '(note . "%t") org-log-note-headings))
 
 (defcustom org-log-into-drawer nil
-  "Non-nil means, insert state change notes and time stamps into a drawer.
+  "Non-nil means insert state change notes and time stamps into a drawer.
 When nil, state changes notes will be inserted after the headline and
 any scheduling and clock lines, but not inside a drawer.
 
@@ -2001,7 +2385,7 @@ used instead of the default value."
      (t p))))
 
 (defcustom org-log-state-notes-insert-after-drawers nil
-  "Non-nil means, insert state change notes after any drawers in entry.
+  "Non-nil means insert state change notes after any drawers in entry.
 Only the drawers that *immediately* follow the headline and the
 deadline/scheduled line are skipped.
 When nil, insert notes right after the heading and perhaps the line
@@ -2014,19 +2398,28 @@ set."
   :type 'boolean)
 
 (defcustom org-log-states-order-reversed t
-  "Non-nil means, the latest state change note will be directly after heading.
-When nil, the notes will be orderer according to time."
+  "Non-nil means the latest state note will be directly after heading.
+When nil, the state change notes will be ordered according to time."
   :group 'org-todo
   :group 'org-progress
   :type 'boolean)
 
+(defcustom org-todo-repeat-to-state nil
+  "The TODO state to which a repeater should return the repeating task.
+By default this is the first task in a TODO sequence, or the previous state
+in a TODO_TYP set.  But you can specify another task here.
+alternatively, set the :REPEAT_TO_STATE: property of the entry."
+  :group 'org-todo
+  :type '(choice (const :tag "Head of sequence" nil)
+                (string :tag "Specific state")))
+
 (defcustom org-log-repeat 'time
-  "Non-nil means, record moving through the DONE state when triggering repeat.
-An auto-repeating tasks  is immediately switched back to TODO when marked
-done.  If you are not logging state changes (by adding \"@\" or \"!\" to
-the TODO keyword definition, or recording a closing note by setting
-`org-log-done', there will be no record of the task moving through DONE.
-This variable forces taking a note anyway.  Possible values are:
+  "Non-nil means record moving through the DONE state when triggering repeat.
+An auto-repeating task is immediately switched back to TODO when
+marked DONE.  If you are not logging state changes (by adding \"@\"
+or \"!\" to the TODO keyword definition), or set `org-log-done' to
+record a closing note, there will be no record of the task moving
+through DONE. This variable forces taking a note anyway.
 
 nil     Don't force a record
 time    Record a time stamp
@@ -2054,7 +2447,7 @@ property to one or more of these keywords."
   :group 'org-todo)
 
 (defcustom org-enable-priority-commands t
-  "Non-nil means, priority commands are active.
+  "Non-nil means priority commands are active.
 When nil, these commands will be disabled, so that you never accidentally
 set a priority."
   :group 'org-priorities
@@ -2079,19 +2472,29 @@ This is the priority an item get if no explicit priority is given."
   :type 'character)
 
 (defcustom org-priority-start-cycle-with-default t
-  "Non-nil means, start with default priority when starting to cycle.
+  "Non-nil means start with default priority when starting to cycle.
 When this is nil, the first step in the cycle will be (depending on the
 command used) one higher or lower that the default priority."
   :group 'org-priorities
   :type 'boolean)
 
+(defcustom org-get-priority-function nil
+  "Function to extract the priority from a string.
+The string is normally the headline.  If this is nil Org computes the
+priority from the priority cookie like [#A] in the headline.  It returns
+an integer, increasing by 1000 for each priority level.
+The user can set a different function here, which should take a string
+as an argument and return the numeric priority."
+  :group 'org-priorities
+  :type 'function)
+
 (defgroup org-time nil
   "Options concerning time stamps and deadlines in Org-mode."
   :tag "Org Time"
   :group 'org)
 
 (defcustom org-insert-labeled-timestamps-at-point nil
-  "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
+  "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
 When nil, these labeled time stamps are forces into the second line of an
 entry, just after the headline.  When scheduling from the global TODO list,
 the time stamp will always be forced into the second line."
@@ -2112,12 +2515,12 @@ of N minutes, as given by the second value.
 When a setting is 0 or 1, insert the time unmodified.  Useful rounding
 numbers should be factors of 60, so for example 5, 10, 15.
 
-When this is larger than 1, you can still force an exact time-stamp by using
-a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
+When this is larger than 1, you can still force an exact time stamp by using
+a double prefix argument to a time stamp command like `C-c .' or `C-c !',
 and by using a prefix arg to `S-up/down' to specify the exact number
 of minutes to shift."
   :group 'org-time
-  :get '(lambda (var) ; Make sure all entries have 5 elements
+  :get '(lambda (var) ; Make sure both elements are there
          (if (integerp (default-value var))
              (list (default-value var) 5)
            (default-value var)))
@@ -2132,7 +2535,7 @@ of minutes to shift."
              org-time-stamp-rounding-minutes)))
 
 (defcustom org-display-custom-times nil
-  "Non-nil means, overlay custom formats over all time stamps.
+  "Non-nil means overlay custom formats over all time stamps.
 The formats are defined through the variable `org-time-stamp-custom-formats'.
 To turn this on on a per-file basis, insert anywhere in the file:
    #+STARTUP: customtime"
@@ -2160,6 +2563,18 @@ commands, if custom time display is turned on at the time of export."
       f)))
 
 (defcustom org-time-clocksum-format "%d:%02d"
+  "The format string used when creating CLOCKSUM lines.
+This is also used when org-mode generates a time duration."
+  :group 'org-time
+  :type 'string)
+
+(defcustom org-time-clocksum-use-fractional nil
+  "If non-nil, \\[org-clock-display] uses fractional times.
+org-mode generates a time duration."
+  :group 'org-time
+  :type 'boolean)
+
+(defcustom org-time-clocksum-fractional-format "%.2f"
   "The format string used when creating CLOCKSUM lines, or when
 org-mode generates a time duration."
   :group 'org-time
@@ -2177,31 +2592,55 @@ Custom commands can set this variable in the options section."
   :type 'integer)
 
 (defcustom org-read-date-prefer-future t
-  "Non-nil means, assume future for incomplete date input from user.
+  "Non-nil means assume future for incomplete date input from user.
 This affects the following situations:
-1. The user gives a day, but no month.
+1. The user gives a month but not a year.
+   For example, if it is April and you enter \"feb 2\", this will be read
+   as Feb 2, *next* year.  \"May 5\", however, will be this year.
+2. The user gives a day, but no month.
    For example, if today is the 15th, and you enter \"3\", Org-mode will
    read this as the third of *next* month.  However, if you enter \"17\",
    it will be considered as *this* month.
-2. The user gives a month but not a year.
-   For example, if it is april and you enter \"feb 2\", this will be read
-   as feb 2, *next* year.  \"May 5\", however, will be this year.
 
-Currently this does not work for ISO week specifications.
+If you set this variable to the symbol `time', then also the following
+will work:
+
+3. If the user gives a time, but no day.  If the time is before now,
+   to will be interpreted as tomorrow.
+
+Currently none of this works for ISO week specifications.
 
-When this option is nil, the current month and year will always be used
-as defaults."
+When this option is nil, the current day, month and year will always be
+used as defaults.
+
+See also `org-agenda-jump-prefer-future'."
   :group 'org-time
-  :type 'boolean)
+  :type '(choice
+         (const :tag "Never" nil)
+         (const :tag "Check month and day" t)
+         (const :tag "Check month, day, and time" time)))
+
+(defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
+  "Should the agenda jump command prefer the future for incomplete dates?
+The default is to do the same as configured in `org-read-date-prefer-future'.
+But you can alse set a deviating value here.
+This may t or nil, or the symbol `org-read-date-prefer-future'."
+  :group 'org-agenda 
+  :group 'org-time 
+  :type '(choice
+         (const :tag "Use org-read-date-prefer-future"
+                org-read-date-prefer-future)
+         (const :tag "Never" nil)
+         (const :tag "Always" t)))
 
 (defcustom org-read-date-display-live t
-  "Non-nil means, display current interpretation of date prompt live.
+  "Non-nil means display current interpretation of date prompt live.
 This display will be in an overlay, in the minibuffer."
   :group 'org-time
   :type 'boolean)
 
 (defcustom org-read-date-popup-calendar t
-  "Non-nil means, pop up a calendar when prompting for a date.
+  "Non-nil means pop up a calendar when prompting for a date.
 In the calendar, the date can be selected with mouse-1.  However, the
 minibuffer will also be active, and you can simply enter the date as well.
 When nil, only the minibuffer will be available."
@@ -2234,13 +2673,13 @@ be the favorite working time of John Wiegley :-)"
   :type 'integer)
 
 (defcustom org-edit-timestamp-down-means-later nil
-  "Non-nil means, S-down will increase the time in a time stamp.
+  "Non-nil means S-down will increase the time in a time stamp.
 When nil, S-up will increase."
   :group 'org-time
   :type 'boolean)
 
 (defcustom org-calendar-follow-timestamp-change t
-  "Non-nil means, make the calendar window follow timestamp changes.
+  "Non-nil means make the calendar window follow timestamp changes.
 When a timestamp is modified and the calendar window is visible, it will be
 moved to the new date."
   :group 'org-time
@@ -2264,8 +2703,12 @@ See the manual for details."
          (choice
           (cons   (string    :tag "Tag name")
                   (character :tag "Access char"))
-          (const :tag "Start radio group" (:startgroup))
-          (const :tag "End radio group" (:endgroup))
+          (list :tag "Start radio group"
+                (const :startgroup)
+                (option (string :tag "Group description")))
+          (list :tag "End radio group"
+                (const :endgroup)
+                (option (string :tag "Group description")))
           (const :tag "New line" (:newline)))))
 
 (defcustom org-tag-persistent-alist nil
@@ -2288,14 +2731,28 @@ To disable these tags on a per-file basis, insert anywhere in the file:
           (const :tag "End radio group" (:endgroup))
           (const :tag "New line" (:newline)))))
 
+(defcustom org-complete-tags-always-offer-all-agenda-tags nil
+  "If non-nil, always offer completion for all tags of all agenda files.
+Instead of customizing this variable directly, you might want to
+set it locally for capture buffers, because there no list of
+tags in that file can be created dynamically (there are none).
+
+  (add-hook 'org-capture-mode-hook
+            (lambda ()
+              (set (make-local-variable
+                    'org-complete-tags-always-offer-all-agenda-tags)
+                   t)))"
+  :group 'org-tags
+  :type 'boolean)
+
 (defvar org-file-tags nil
   "List of tags that can be inherited by all entries in the file.
 The tags will be inherited if the variable `org-use-tag-inheritance'
 says they should be.
-This variable is populated from #+TAG lines.")
+This variable is populated from #+FILETAGS lines.")
 
 (defcustom org-use-fast-tag-selection 'auto
-  "Non-nil means, use fast tag selection scheme.
+  "Non-nil means use fast tag selection scheme.
 This is a special interface to select and deselect tags with single keys.
 When nil, fast selection is never used.
 When the symbol `auto', fast selection is used if and only if selection
@@ -2310,7 +2767,7 @@ automatically if necessary."
          (const :tag "When selection characters are configured" 'auto)))
 
 (defcustom org-fast-tag-selection-single-key nil
-  "Non-nil means, fast tag selection exits after first change.
+  "Non-nil means fast tag selection exits after first change.
 When nil, you have to press RET to exit it.
 During fast tag selection, you can toggle this flag with `C-c'.
 This variable can also have the value `expert'.  In this case, the window
@@ -2322,7 +2779,7 @@ displaying the tags menu is not even shown, until you press C-c again."
          (const :tag "Expert" expert)))
 
 (defvar org-fast-tag-selection-include-todo nil
-  "Non-nil means, fast tags selection interface will also offer TODO states.
+  "Non-nil means fast tags selection interface will also offer TODO states.
 This is an undocumented feature, you should not rely on it.")
 
 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
@@ -2334,7 +2791,7 @@ it means that the tags should be flushright to that column.  For example,
   :type 'integer)
 
 (defcustom org-auto-align-tags t
-  "Non-nil means, realign tags after pro/demotion of TODO state change.
+  "Non-nil means realign tags after pro/demotion of TODO state change.
 These operations change the length of a headline and therefore shift
 the tags around.  With this options turned on, after each such operation
 the tags are again aligned to `org-tags-column'."
@@ -2342,7 +2799,7 @@ the tags are again aligned to `org-tags-column'."
   :type 'boolean)
 
 (defcustom org-use-tag-inheritance t
-  "Non-nil means, tags in levels apply also for sublevels.
+  "Non-nil means tags in levels apply also for sublevels.
 When nil, only the tags directly given in a specific line apply there.
 This may also be a list of tags that should be inherited, or a regexp that
 matches tags that should be inherited.  Additional control is possible
@@ -2404,7 +2861,7 @@ is better to limit inheritance to certain tags using the variables
          (const :tag "List them, indented with leading dots" indented)))
 
 (defcustom org-tags-sort-function nil
-  "When set, tags are sorted using this function as a comparator"
+  "When set, tags are sorted using this function as a comparator."
   :group 'org-tags
   :type '(choice
          (const :tag "No sorting" nil)
@@ -2433,9 +2890,9 @@ lined-up with respect to each other."
   :type 'string)
 
 (defcustom org-use-property-inheritance nil
-  "Non-nil means, properties apply also for sublevels.
+  "Non-nil means properties apply also for sublevels.
 
-This setting is chiefly used during property searches. Turning it on can
+This setting is chiefly used during property searches.  Turning it on can
 cause significant overhead when doing a search, which is why it is not
 on by default.
 
@@ -2577,7 +3034,9 @@ If an entry is a directory, all files in that directory that are matched by
 
 If the value of the variable is not a list but a single file name, then
 the list of agenda files is actually stored and maintained in that file, one
-agenda file per line."
+agenda file per line.  In this file paths can be given relative to
+`org-directory'.  Tilde expansion and environment variable substitution
+are also made."
   :group 'org-agenda
   :type '(choice
          (repeat :tag "List of files and directories" file)
@@ -2632,12 +3091,39 @@ default is the character `k' because we use the same key in the agenda."
   :group 'org-agenda
   :type 'sexp)
 
+(defcustom org-calendar-insert-diary-entry-key [?i]
+  "The key to be installed in `calendar-mode-map' for adding diary entries.
+This option is irrelevant until `org-agenda-diary-file' has been configured
+to point to an Org-mode file.  When that is the case, the command
+`org-agenda-diary-entry' will be bound to the key given here, by default
+`i'.  In the calendar, `i' normally adds entries to `diary-file'.  So
+if you want to continue doing this, you need to change this to a different
+key."
+  :group 'org-agenda
+  :type 'sexp)
+
+(defcustom org-agenda-diary-file 'diary-file
+  "File to which to add new entries with the `i' key in agenda and calendar.
+When this is the symbol `diary-file', the functionality in the Emacs
+calendar will be used to add entries to the `diary-file'.  But when this
+points to a file, `org-agenda-diary-entry' will be used instead."
+  :group 'org-agenda
+  :type '(choice
+         (const :tag "The standard Emacs diary file" diary-file)
+         (file :tag "Special Org file diary entries")))
+
 (eval-after-load "calendar"
   '(progn
      (org-defkey calendar-mode-map org-calendar-to-agenda-key
                 'org-calendar-goto-agenda)
      (org-defkey calendar-mode-map org-calendar-agenda-action-key
-                'org-agenda-action)))
+                'org-agenda-action)
+     (add-hook 'calendar-mode-hook
+              (lambda ()
+                (unless (eq org-agenda-diary-file 'diary-file)
+                  (define-key calendar-mode-map
+                    org-calendar-insert-diary-entry-key
+                    'org-agenda-diary-entry))))))
 
 (defgroup org-latex nil
   "Options for embedding LaTeX code into Org-mode."
@@ -2646,15 +3132,15 @@ default is the character `k' because we use the same key in the agenda."
 
 (defcustom org-format-latex-options
   '(:foreground default :background default :scale 1.0
-    :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
-    :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
+    :html-foreground "Black" :html-background "Transparent"
+    :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
   "Options for creating images from LaTeX fragments.
 This is a property list with the following properties:
 :foreground  the foreground color for images embedded in Emacs, e.g. \"Black\".
              `default' means use the foreground 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.
+:scale       a scaling factor for the size of the images, to get more pixels
 :html-foreground, :html-background, :html-scale
              the same numbers for HTML export.
 :matchers    a list indicating which matchers should be used to
@@ -2668,22 +3154,138 @@ This is a property list with the following properties:
   :group 'org-latex
   :type 'plist)
 
+(defcustom org-format-latex-signal-error t
+  "Non-nil means signal an error when image creation of LaTeX snippets fails.
+When nil, just push out a message."
+  :group 'org-latex
+  :type 'boolean)
+
 (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."
+\\pagestyle{empty}             % do not remove
+\[PACKAGES]
+\[DEFAULT-PACKAGES]
+% The settings below are copied from fullpage.sty
+\\setlength{\\textwidth}{\\paperwidth}
+\\addtolength{\\textwidth}{-3cm}
+\\setlength{\\oddsidemargin}{1.5cm}
+\\addtolength{\\oddsidemargin}{-2.54cm}
+\\setlength{\\evensidemargin}{\\oddsidemargin}
+\\setlength{\\textheight}{\\paperheight}
+\\addtolength{\\textheight}{-\\headheight}
+\\addtolength{\\textheight}{-\\headsep}
+\\addtolength{\\textheight}{-\\footskip}
+\\addtolength{\\textheight}{-3cm}
+\\setlength{\\topmargin}{1.5cm}
+\\addtolength{\\topmargin}{-2.54cm}"
+  "The document header used for processing LaTeX fragments.
+It is imperative that this header make sure that no page number
+appears on the page.  The package defined in the variables
+`org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
+will either replace the placeholder \"[PACKAGES]\" in this header, or they
+will be appended."
   :group 'org-latex
   :type 'string)
 
+(defvar org-format-latex-header-extra nil)
+
+(defun org-set-packages-alist (var val)
+  "Set the packages alist and make sure it has 3 elements per entry."
+  (set var (mapcar (lambda (x)
+                    (if (and (consp x) (= (length x) 2))
+                        (list (car x) (nth 1 x) t)
+                      x))
+                  val)))
+
+(defun org-get-packages-alist (var)
+
+  "Get the packages alist and make sure it has 3 elements per entry."
+  (mapcar (lambda (x)
+           (if (and (consp x) (= (length x) 2))
+               (list (car x) (nth 1 x) t)
+             x))
+         (default-value var)))
+
+;; The following variables are defined here because is it also used
+;; when formatting latex fragments.  Originally it was part of the
+;; LaTeX exporter, which is why the name includes "export".
+(defcustom org-export-latex-default-packages-alist
+  '(("AUTO" "inputenc"  t)
+    ("T1"   "fontenc"   t)
+    (""     "fixltx2e"  nil)
+    (""     "graphicx"  t)
+    (""     "longtable" nil)
+    (""     "float"     nil)
+    (""     "wrapfig"   nil)
+    (""     "soul"      t)
+    (""     "textcomp"  t)
+    (""     "marvosym"  t)
+    (""     "wasysym"   t)
+    (""     "latexsym"  t)
+    (""     "amssymb"   t)
+    (""     "hyperref"  nil)
+    "\\tolerance=1000"
+    )
+  "Alist of default packages to be inserted in the header.
+Change this only if one of the packages here causes an incompatibility
+with another package you are using.
+The packages in this list are needed by one part or another of Org-mode
+to function properly.
+
+- inputenc, fontenc:  for basic font and character selection
+- textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
+  for interpreting the entities in `org-entities'.  You can skip some of these
+  packages if you don't use any of the symbols in it.
+- graphicx: for including images
+- float, wrapfig: for figure placement
+- longtable: for long tables
+- hyperref: for cross references
+
+Therefore you should not modify this variable unless you know what you
+are doing.  The one reason to change it anyway is that you might be loading
+some other package that conflicts with one of the default packages.
+Each cell is of the format \( \"options\" \"package\" snippet-flag\).
+If SNIPPET-FLAG is t, the package also needs to be included when
+compiling LaTeX snippets into images for inclusion into HTML."
+  :group 'org-export-latex
+  :set 'org-set-packages-alist
+  :get 'org-get-packages-alist
+  :type '(repeat
+         (choice
+          (list :tag "options/package pair"
+                (string :tag "options")
+                (string :tag "package")
+                (boolean :tag "Snippet"))
+          (string :tag "A line of LaTeX"))))
+
+(defcustom org-export-latex-packages-alist nil
+  "Alist of packages to be inserted in every LaTeX header.
+These will be inserted after `org-export-latex-default-packages-alist'.
+Each cell is of the format \( \"options\" \"package\" snippet-flag \).
+SNIPPET-FLAG, when t, indicates that this package is also needed when
+turning LaTeX snippets into images for inclusion into HTML.
+Make sure that you only list packages here which:
+- you want in every file
+- do not conflict with the default packages in
+  `org-export-latex-default-packages-alist'
+- do not conflict with the setup in `org-format-latex-header'."
+  :group 'org-export-latex
+  :set 'org-set-packages-alist
+  :get 'org-get-packages-alist
+  :type '(repeat
+         (choice
+          (list :tag "options/package pair"
+                (string :tag "options")
+                (string :tag "package")
+                (boolean :tag "Snippet"))
+          (string :tag "A line of LaTeX"))))
 
-(defgroup org-font-lock nil
-  "Font-lock settings for highlighting in Org-mode."
-  :tag "Org Font Lock"
+
+(defgroup org-appearance nil
+  "Settings for Org-mode appearance."
+  :tag "Org Appearance"
   :group 'org)
 
 (defcustom org-level-color-stars-only nil
@@ -2691,11 +3293,11 @@ This is a property list with the following properties:
 When nil, the entire headline is fontified.
 Changing it requires restart of `font-lock-mode' to become effective
 also in regions already fontified."
-  :group 'org-font-lock
+  :group 'org-appearance
   :type 'boolean)
 
 (defcustom org-hide-leading-stars nil
-  "Non-nil means, hide the first N-1 stars in a headline.
+  "Non-nil means hide the first N-1 stars in a headline.
 This works by using the face `org-hide' for these stars.  This
 face is white for a light background, and black for a dark
 background.  You may have to customize the face `org-hide' to
@@ -2707,42 +3309,72 @@ lines to the buffer:
 
    #+STARTUP: hidestars
    #+STARTUP: showstars"
-  :group 'org-font-lock
+  :group 'org-appearance
   :type 'boolean)
 
+(defcustom org-hidden-keywords nil
+  "List of keywords that should be hidden when typed in the org buffer.
+For example, add #+TITLE to this list in order to make the
+document title appear in the buffer without the initial #+TITLE:
+keyword."
+  :group 'org-appearance
+  :type '(set (const :tag "#+AUTHOR" author)
+             (const :tag "#+DATE" date)
+             (const :tag "#+EMAIL" email)
+             (const :tag "#+TITLE"  title)))
+
 (defcustom org-fontify-done-headline nil
-  "Non-nil means, change the face of a headline if it is marked DONE.
+  "Non-nil means change the face of a headline if it is marked DONE.
 Normally, only the TODO/DONE keyword indicates the state of a headline.
 When this is non-nil, the headline after the keyword is set to the
 `org-headline-done' as an additional indication."
-  :group 'org-font-lock
+  :group 'org-appearance
   :type 'boolean)
 
 (defcustom org-fontify-emphasized-text t
   "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
 Changing this variable requires a restart of Emacs to take effect."
-  :group 'org-font-lock
+  :group 'org-appearance
   :type 'boolean)
 
 (defcustom org-fontify-whole-heading-line nil
   "Non-nil means fontify the whole line for headings.
 This is useful when setting a background color for the
-org-leve-* faces."
-  :group 'org-font-lock
+org-level-* faces."
+  :group 'org-appearance
   :type 'boolean)
 
 (defcustom org-highlight-latex-fragments-and-specials nil
-  "Non-nil means, fontify what is treated specially by the exporters."
-  :group 'org-font-lock
+  "Non-nil means fontify what is treated specially by the exporters."
+  :group 'org-appearance
   :type 'boolean)
 
 (defcustom org-hide-emphasis-markers nil
   "Non-nil mean font-lock should hide the emphasis marker characters."
-  :group 'org-font-lock
+  :group 'org-appearance
+  :type 'boolean)
+
+(defcustom org-pretty-entities nil
+  "Non-nil means show entities as UTF8 characters.
+When nil, the \\name form remains in the buffer."
+  :group 'org-appearance
+  :type 'boolean)
+
+(defcustom org-pretty-entities-include-sub-superscripts t
+  "Non-nil means, pretty entity display includes formatting sub/superscripts."
+  :group 'org-appearance
   :type 'boolean)
 
 (defvar org-emph-re nil
-  "Regular expression for matching emphasis.")
+  "Regular expression for matching emphasis.
+After a match, the match groups contain these elements:
+0  The match of the full regular expression, including the characters
+     before and after the proper match
+1  The character before the proper match, or empty at beginning of line
+2  The proper match, including the leading and trailing markers
+3  The leading marker like * or /, indicating the type of highlighting
+4  The text between the emphasis markers, not including the markers
+5  The character after the match, empty at the end of a line")
 (defvar org-verbatim-re nil
   "Regular expression for matching verbatim text.")
 (defvar org-emphasis-regexp-components) ; defined just below
@@ -2805,7 +3437,7 @@ org-leve-* faces."
 (defcustom org-emphasis-regexp-components
   '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
   "Components used to build the regular expression for emphasis.
-This is a list with 6 entries.  Terminology:  In an emphasis string
+This is a list with five entries.  Terminology:  In an emphasis string
 like \" *strong word* \", we call the initial space PREMATCH, the final
 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
 and \"trong wor\" is the body.  The different components in this variable
@@ -2819,7 +3451,7 @@ body-regexp  A regexp like \".\" to match a body character.  Don't use
 newline      The maximum number of newlines allowed in an emphasis exp.
 
 Use customize to modify this, or restart Emacs after changing it."
-  :group 'org-font-lock
+  :group 'org-appearance
   :set 'org-set-emph-re
   :type '(list
          (sexp    :tag "Allowed chars in pre      ")
@@ -2844,8 +3476,9 @@ example *bold*, _underlined_ and /italic/.  This variable sets the marker
 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.
 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
+For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
 Use customize to modify this, or restart Emacs after changing it."
-  :group 'org-font-lock
+  :group 'org-appearance
   :set 'org-set-emph-re
   :type '(repeat
          (list
@@ -2870,7 +3503,7 @@ This is needed for font-lock setup.")
   :group 'org)
 
 (defcustom org-completion-use-ido nil
-  "Non-nil means, use ido completion wherever possible.
+  "Non-nil means use ido completion wherever possible.
 Note that `ido-mode' must be active for this variable to be relevant.
 If you decide to turn this variable on, you might well want to turn off
 `org-outline-path-complete-in-steps'.
@@ -2879,21 +3512,21 @@ See also `org-completion-use-iswitchb'."
   :type 'boolean)
 
 (defcustom org-completion-use-iswitchb nil
-  "Non-nil means, use iswitchb completion wherever possible.
+  "Non-nil means use iswitchb completion wherever possible.
 Note that `iswitchb-mode' must be active for this variable to be relevant.
 If you decide to turn this variable on, you might well want to turn off
 `org-outline-path-complete-in-steps'.
-Note that thi variable has only an effect if `org-completion-use-ido' is nil."
+Note that this variable has only an effect if `org-completion-use-ido' is nil."
   :group 'org-completion
   :type 'boolean)
 
 (defcustom org-completion-fallback-command 'hippie-expand
-  "The expansion command called by \\[org-complete] in normal context.
+  "The expansion command called by \\[pcomplete] in normal context.
 Normal means, no org-mode-specific context."
   :group 'org-completion
   :type 'function)
 
-;;; Functions and variables from ther packages
+;;; Functions and variables from their packages
 ;;  Declared here to avoid compiler warnings
 
 ;; XEmacs only
@@ -2916,14 +3549,15 @@ Normal means, no org-mode-specific context."
 (declare-function cdlatex-tab "ext:cdlatex" ())
 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
 (defvar font-lock-unfontify-region-function)
-(declare-function iswitchb-mode "iswitchb" (&optional arg))
-(declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
+(declare-function iswitchb-read-buffer "iswitchb"
+                  (prompt &optional default require-match start matches-set))
 (defvar iswitchb-temp-buflist)
 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
 (defvar org-agenda-tags-todo-honor-ignore-options)
 (declare-function org-agenda-skip "org-agenda" ())
-(declare-function org-format-agenda-item "org-agenda"
-                 (extra txt &optional category tags dotime noprefix remove-re))
+(declare-function
+ org-format-agenda-item "org-agenda"
+ (extra txt &optional category tags dotime noprefix remove-re habitp))
 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
 (declare-function org-agenda-change-all-lines "org-agenda"
                  (newhead hdmarker &optional fixface just-this))
@@ -2935,17 +3569,15 @@ Normal means, no org-mode-specific context."
 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
                  "org-agenda" (&optional end))
 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
-(declare-function org-indent-mode "org-indent" (arg))
+(declare-function org-inlinetask-in-task-p "org-inlinetask" ())
+(declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
+(declare-function org-inlinetask-goto-end "org-inlinetask" ())
+(declare-function org-indent-mode "org-indent" (&optional arg))
 (declare-function parse-time-string "parse-time" (string))
-(declare-function remember "remember" (&optional initial))
-(declare-function remember-buffer-desc "remember" ())
-(declare-function remember-finalize "remember" ())
-(defvar remember-save-after-remembering)
+(declare-function org-attach-reveal "org-attach" (&optional if-exists))
+(declare-function org-export-latex-fix-inputenc "org-latex" ())
+(declare-function orgtbl-send-table "org-table" (&optional maybe))
 (defvar remember-data-file)
-(defvar remember-register)
-(defvar remember-buffer)
-(defvar remember-handler-functions)
-(defvar remember-annotation-functions)
 (defvar texmathp-why)
 (declare-function speedbar-line-directory "speedbar" (&optional depth))
 (declare-function table--at-cell-p "table" (position &optional object at-column))
@@ -2961,18 +3593,18 @@ Normal means, no org-mode-specific context."
 ;; by the functions setting up org-mode or checking for table context.
 
 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
-  "Detects an org-type or table-type table.")
+  "Detect an org-type or table-type table.")
 (defconst org-table-line-regexp "^[ \t]*|"
-  "Detects an org-type table line.")
+  "Detect an org-type table line.")
 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
-  "Detects an org-type table line.")
+  "Detect an org-type table line.")
 (defconst org-table-hline-regexp "^[ \t]*|-"
-  "Detects an org-type table hline.")
+  "Detect an org-type table hline.")
 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
-  "Detects a table-type table hline.")
+  "Detect a table-type table hline.")
 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
-  "Searching from within a table (any type) this finds the first line
-outside the table.")
+  "Detect the first line outside a table when searching from within it.
+This works for both table types.")
 
 ;; Autoload the functions in org-table.el that are needed by functions here.
 
@@ -2999,7 +3631,9 @@ outside the table.")
    org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
    org-table-toggle-coordinate-overlays
    org-table-toggle-formula-debugger org-table-wrap-region
-   orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
+   orgtbl-mode turn-on-orgtbl org-table-to-lisp
+   orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
+   orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
 
 (defun org-at-table-p (&optional table-type)
   "Return t if the cursor is inside an org-type table.
@@ -3039,7 +3673,7 @@ If TABLE-TYPE is non-nil, also check for table.el-type tables."
                    (message "recognizing table.el table...")
                    (table-recognize-table)
                    (message "recognizing table.el table...done")))
-             (error "This should not happen..."))
+             (error "This should not happen"))
            t)
        nil)
     nil))
@@ -3054,21 +3688,22 @@ If TABLE-TYPE is non-nil, also check for table.el-type tables."
 
 (defvar org-table-clean-did-remove-column nil)
 
-(defun org-table-map-tables (function)
+(defun org-table-map-tables (function &optional quietly)
   "Apply FUNCTION to the start of all tables in the buffer."
   (save-excursion
     (save-restriction
       (widen)
       (goto-char (point-min))
       (while (re-search-forward org-table-any-line-regexp nil t)
-       (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
+       (unless quietly
+         (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
        (beginning-of-line 1)
        (when (looking-at org-table-line-regexp)
          (save-excursion (funcall function))
          (or (looking-at org-table-line-regexp)
              (forward-char 1)))
        (re-search-forward org-table-any-border-regexp nil 1))))
-  (message "Mapping tables: done"))
+  (unless quietly (message "Mapping tables: done")))
 
 ;; Declare and autoload functions from org-exp.el  & Co
 
@@ -3084,16 +3719,27 @@ If TABLE-TYPE is non-nil, also check for table.el-type tables."
                '(org-export-as-ascii org-export-ascii-preprocess
                  org-export-as-ascii-to-buffer org-replace-region-by-ascii
                  org-export-region-as-ascii))
+  (org-autoload "org-latex"
+               '(org-export-as-latex-batch org-export-as-latex-to-buffer
+                  org-replace-region-by-latex org-export-region-as-latex
+                 org-export-as-latex org-export-as-pdf
+                 org-export-as-pdf-and-open))
   (org-autoload "org-html"
                '(org-export-as-html-and-open
                  org-export-as-html-batch org-export-as-html-to-buffer
                  org-replace-region-by-html org-export-region-as-html
                  org-export-as-html))
+  (org-autoload "org-docbook"
+               '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
+                 org-replace-region-by-docbook org-export-region-as-docbook
+                 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
+                 org-export-as-docbook))
   (org-autoload "org-icalendar"
                '(org-export-icalendar-this-file
                  org-export-icalendar-all-agenda-files
                  org-export-icalendar-combine-agenda-files))
-  (org-autoload "org-xoxo" '(org-export-as-xoxo)))
+  (org-autoload "org-xoxo" '(org-export-as-xoxo))
+  (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
 
 ;; Declare and autoload functions from org-agenda.el
 
@@ -3111,17 +3757,25 @@ If TABLE-TYPE is non-nil, also check for table.el-type tables."
                '(org-remember-insinuate org-remember-annotation
    org-remember-apply-template org-remember org-remember-handler)))
 
-;; Autoload org-clock.el
+(eval-and-compile
+  (org-autoload "org-capture"
+               '(org-capture org-capture-insert-template-here
+                  org-capture-import-remember-templates)))
 
+;; Autoload org-clock.el
 
 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
                  (beg end))
 (declare-function org-clock-update-mode-line "org-clock" ())
+(declare-function org-resolve-clocks "org-clock"
+                 (&optional also-non-dangling-p prompt last-valid))
 (defvar org-clock-start-time)
 (defvar org-clock-marker (make-marker)
   "Marker recording the last clock-in.")
 (defvar org-clock-hd-marker (make-marker)
   "Marker recording the last clock-in, but the headline position.")
+(defvar org-clock-heading ""
+  "The heading of the current clock entry.")
 (defun org-clock-is-active ()
  "Return non-nil if clock is currently running.
 The return value is actually the clock marker."
@@ -3134,7 +3788,7 @@ The return value is actually the clock marker."
                  org-clock-goto org-clock-sum org-clock-display
                  org-clock-remove-overlays org-clock-report
                  org-clocktable-shift org-dblock-write:clocktable
-                 org-get-clocktable)))
+                 org-get-clocktable org-resolve-clocks)))
 
 (defun org-clock-update-time-maybe ()
   "If this is a CLOCK line, update it and return t.
@@ -3214,11 +3868,23 @@ If yes, offer to stop it and to save the buffer with the changes."
 
 ;; Autoload org-indent.el
 
+;; Define the variable already here, to make sure we have it.
+(defvar org-indent-mode nil
+  "Non-nil if Org-Indent mode is enabled.
+Use the command `org-indent-mode' to change this variable.")
+
 (eval-and-compile
   (org-autoload
    "org-indent"
    '(org-indent-mode)))
 
+;; Autoload org-mobile.el
+
+(eval-and-compile
+  (org-autoload
+   "org-mobile"
+   '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
+
 ;; Autoload archiving code
 ;; The stuff that is needed for cycling and tags has to be defined here.
 
@@ -3259,7 +3925,7 @@ Here are a few examples:
        Archive in file ~/org/archive.org (absolute path), as top-level trees.
 
 \"~/org/archive.org::From %s\"
-       Archive in file ~/org/archive.org (absolute path), und headlines
+       Archive in file ~/org/archive.org (absolute path), under headlines
         \"From FILENAME\" where file name is the current file name.
 
 \"basement::** Finished Tasks\"
@@ -3288,7 +3954,7 @@ get the proper fontification."
   :type 'string)
 
 (defcustom org-agenda-skip-archived-trees t
-  "Non-nil means, the agenda will skip any items located in archived trees.
+  "Non-nil means the agenda will skip any items located in archived trees.
 An archived tree is a tree marked with the tag ARCHIVE.  The use of this
 variable is no longer recommended, you should leave it at the value t.
 Instead, use the key `v' to cycle the archives-mode in the agenda."
@@ -3296,14 +3962,14 @@ Instead, use the key `v' to cycle the archives-mode in the agenda."
   :group 'org-agenda-skip
   :type 'boolean)
 
-(defcustom org-columns-skip-arrchived-trees t
-  "Non-nil means, irgnore archived trees when creating column view."
+(defcustom org-columns-skip-archived-trees t
+  "Non-nil means ignore archived trees when creating column view."
   :group 'org-archive
   :group 'org-properties
   :type 'boolean)
 
 (defcustom org-cycle-open-archived-trees nil
-  "Non-nil means, `org-cycle' will open archived trees.
+  "Non-nil means `org-cycle' will open archived trees.
 An archived tree is a tree marked with the tag ARCHIVE.
 When nil, archived trees will stay folded.  You can still open them with
 normal outline commands like `show-all', but not with the cycling commands."
@@ -3346,15 +4012,26 @@ collapsed state."
     (let* ((re (concat ":" org-archive-tag ":")))
       (goto-char beg)
       (while (re-search-forward re end t)
-       (and (org-on-heading-p) (hide-subtree))
-       (org-end-of-subtree t)))))
+       (when (org-on-heading-p)
+         (org-flag-subtree t)
+         (org-end-of-subtree t))))))
+
+(defun org-flag-subtree (flag)
+  (save-excursion
+    (org-back-to-heading t)
+    (outline-end-of-heading)
+    (outline-flag-region (point)
+                        (progn (org-end-of-subtree t) (point))
+                        flag)))
 
 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
 
 (eval-and-compile
   (org-autoload "org-archive"
    '(org-add-archive-files org-archive-subtree
-     org-archive-to-archive-sibling org-toggle-archive-tag)))
+     org-archive-to-archive-sibling org-toggle-archive-tag
+     org-archive-subtree-default
+     org-archive-subtree-default-with-confirmation)))
 
 ;; Autoload Column View Code
 
@@ -3376,7 +4053,7 @@ collapsed state."
 (org-autoload "org-id"
  '(org-id-get-create org-id-new org-id-copy org-id-get
    org-id-get-with-outline-path-completion
-   org-id-get-with-outline-drilling
+   org-id-get-with-outline-drilling org-id-store-link
    org-id-goto org-id-find org-id-store-link))
 
 ;; Autoload Plotting Code
@@ -3409,6 +4086,12 @@ group 3: Priority cookie
 group 4: True headline
 group 5: Tags")
 (make-variable-buffer-local 'org-complex-heading-regexp)
+(defvar org-complex-heading-regexp-format nil
+  "Printf format to make regexp to match an exact headline.
+This regexp will match the headline of any node which hase the exact
+headline text that is put into the format, but may have any TODO state,
+priority and tags.")
+(make-variable-buffer-local 'org-complex-heading-regexp-format)
 (defvar org-todo-line-tags-regexp nil
   "Matches a headline and puts TODO state into group 2 if present.
 Also put tags into group 4 if tags are present.")
@@ -3448,11 +4131,14 @@ Also put tags into group 4 if tags are present.")
   "Matches any of the 3 keywords, together with the time stamp.")
 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
 (defvar org-maybe-keyword-time-regexp nil
-  "Matches a timestamp, possibly preceeded by a keyword.")
+  "Matches a timestamp, possibly preceded 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)
+(defvar org-all-time-keywords nil
+  "List of time keywords.")
+(make-variable-buffer-local 'org-all-time-keywords)
 
 (defconst org-plain-time-of-day-regexp
   (concat
@@ -3490,7 +4176,7 @@ groups carry important information:
   "Regular expression to match a timestamp time or time range.
 After a match, the following groups carry important information:
 0  the full match
-1  date plus weekday, for backreferencing to make sure both times on same day
+1  date plus weekday, for back referencing to make sure both times are on the same day
 2  the first time, range or not
 4  the second time, if it is a range.")
 
@@ -3499,6 +4185,7 @@ After a match, the following groups carry important information:
     ("overview" org-startup-folded t)
     ("nofold" org-startup-folded nil)
     ("showall" org-startup-folded nil)
+    ("showeverything" org-startup-folded showeverything)
     ("content" org-startup-folded content)
     ("indent" org-startup-indented t)
     ("noindent" org-startup-indented nil)
@@ -3508,6 +4195,8 @@ After a match, the following groups carry important information:
     ("oddeven" org-odd-levels-only nil)
     ("align" org-startup-align-all-tables t)
     ("noalign" org-startup-align-all-tables nil)
+    ("inlineimages" org-startup-with-inline-images t)
+    ("noinlineimages" org-startup-with-inline-images nil)
     ("customtime" org-display-custom-times t)
     ("logdone" org-log-done time)
     ("lognotedone" org-log-done note)
@@ -3517,6 +4206,15 @@ After a match, the following groups carry important information:
     ("logrepeat" org-log-repeat state)
     ("lognoterepeat" org-log-repeat note)
     ("nologrepeat" org-log-repeat nil)
+    ("logreschedule" org-log-reschedule time)
+    ("lognotereschedule" org-log-reschedule note)
+    ("nologreschedule" org-log-reschedule nil)
+    ("logredeadline" org-log-redeadline time)
+    ("lognoteredeadline" org-log-redeadline note)
+    ("nologredeadline" org-log-redeadline nil)
+    ("logrefile" org-log-refile time)
+    ("lognoterefile" org-log-refile note)
+    ("nologrefile" org-log-refile nil)
     ("fninline" org-footnote-define-inline t)
     ("nofninline" org-footnote-define-inline nil)
     ("fnlocal" org-footnote-section nil)
@@ -3530,7 +4228,10 @@ After a match, the following groups carry important information:
     ("constSI" constants-unit-system SI)
     ("noptag" org-tag-persistent-alist nil)
     ("hideblocks" org-hide-block-startup t)
-    ("nohideblocks" org-hide-block-startup nil))
+    ("nohideblocks" org-hide-block-startup nil)
+    ("beamer" org-startup-with-beamer-mode t)
+    ("entitiespretty" org-pretty-entities t)
+    ("entitiesplain" org-pretty-entities nil))
   "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
@@ -3553,11 +4254,13 @@ means to push this value onto the list in the variable.")
     (let ((re (org-make-options-regexp
               '("CATEGORY" "TODO" "COLUMNS"
                 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
-                "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
+                "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
+                "OPTIONS")
               "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
          (splitre "[ \t]+")
+         (scripts org-use-sub-superscripts)
          kwds kws0 kwsa key log value cat arch tags const links hw dws
-         tail sep kws1 prio props ftags drawers
+         tail sep kws1 prio props ftags drawers beamer-p
          ext-setup-or-nil setup-contents (start 0))
       (save-excursion
        (save-restriction
@@ -3570,10 +4273,9 @@ means to push this value onto the list in the variable.")
                          (re-search-forward re nil t)))
            (setq key (upcase (match-string 1 ext-setup-or-nil))
                  value (org-match-string-no-properties 2 ext-setup-or-nil))
+           (if (stringp value) (setq value (org-trim value)))
            (cond
             ((equal key "CATEGORY")
-             (if (string-match "[ \t]+$" value)
-                 (setq value (replace-match "" t t value)))
              (setq cat value))
             ((member key '("SEQ_TODO" "TODO"))
              (push (cons 'sequence (org-split-string value splitre)) kwds))
@@ -3624,10 +4326,14 @@ means to push this value onto the list in the variable.")
                      (set (make-local-variable var) (symbol-value var))
                      (add-to-list var val))))))
             ((equal key "ARCHIVE")
-             (string-match " *$" value)
-             (setq arch (replace-match "" t t value))
+             (setq arch value)
              (remove-text-properties 0 (length arch)
                                      '(face t fontified t) arch))
+            ((equal key "LATEX_CLASS")
+             (setq beamer-p (equal value "beamer")))
+            ((equal key "OPTIONS")
+             (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
+                 (setq scripts (read (match-string 2 value)))))
             ((equal key "SETUPFILE")
              (setq setup-contents (org-file-contents
                                    (expand-file-name
@@ -3640,6 +4346,7 @@ means to push this value onto the list in the variable.")
                              "\n" setup-contents "\n"
                              (substring ext-setup-or-nil start)))))
             ))))
+      (org-set-local 'org-use-sub-superscripts scripts)
       (when cat
        (org-set-local 'org-category (intern cat))
        (push (cons "CATEGORY" cat) props))
@@ -3718,7 +4425,7 @@ means to push this value onto the list in the variable.")
             ((equal e "{") (push '(:startgroup) tgs))
             ((equal e "}") (push '(:endgroup) tgs))
             ((equal e "\\n") (push '(:newline) tgs))
-            ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
+            ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
              (push (cons (match-string 1 e)
                          (string-to-char (match-string 2 e)))
                    tgs))
@@ -3762,7 +4469,16 @@ means to push this value onto the list in the variable.")
            (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
                    (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
                    "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
-                   "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
+                   "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
+           org-complex-heading-regexp-format
+           (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
+                   (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
+                   "\\)\\>\\)?"
+                   "\\(?:[ \t]*\\(\\[#.\\]\\)\\)?"
+                   "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
+                   "[ \t]*\\(%s\\)"
+                   "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
+                   "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?[ \t]*$")
            org-nl-done-regexp
            (concat "\n\\*+[ \t]+"
                    "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
@@ -3771,7 +4487,7 @@ means to push this value onto the list in the variable.")
            (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
                    (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
                    (org-re
-                    "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
+                    "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@#%]+:[ \t]*\\)?$\\)"))
            org-looking-at-done-regexp
            (concat "^" "\\(?:"
                    (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
@@ -3810,6 +4526,10 @@ means to push this value onto the list in the variable.")
                    "\\|" org-deadline-string
                    "\\|" org-closed-string "\\|" org-clock-string
                    "\\)\\>\\)")
+           org-all-time-keywords
+           (mapcar (lambda (w) (substring w 0 -1))
+                   (list org-scheduled-string org-deadline-string
+                         org-clock-string org-closed-string))
            )
       (org-compute-latex-and-specials-regexp)
       (org-set-font-lock-defaults))))
@@ -3820,10 +4540,10 @@ means to push this value onto the list in the variable.")
          (not (file-readable-p file)))
       (if noerror
          (progn
-           (message "Cannot read file %s" file)
+           (message "Cannot read file \"%s\"" file)
            (ding) (sit-for 2)
            "")
-       (error "Cannot read file %s" file))
+       (error "Cannot read file \"%s\"" file))
     (with-temp-buffer
       (insert-file-contents file)
       (buffer-string))))
@@ -3850,36 +4570,32 @@ This will extract info from a string like \"WAIT(w@/!)\"."
              x))
          list))
 
-;; FIXME: this could be done much better, using second characters etc.
 (defun org-assign-fast-keys (alist)
   "Assign fast keys to a keyword-key alist.
 Respect keys that are already there."
-  (let (new e k c c1 c2 (char ?a))
+  (let (new e (alt ?0))
     (while (setq e (pop alist))
-      (cond
-       ((equal e '(:startgroup)) (push e new))
-       ((equal e '(:endgroup)) (push e new))
-       ((equal e '(:newline)) (push e new))
-       (t
-       (setq k (car e) c2 nil)
-       (if (cdr e)
-           (setq c (cdr e))
-         ;; automatically assign a character.
-         (setq c1 (string-to-char
-                   (downcase (substring
-                              k (if (= (string-to-char k) ?@) 1 0)))))
-         (if (or (rassoc c1 new) (rassoc c1 alist))
-             (while (or (rassoc char new) (rassoc char alist))
-               (setq char (1+ char)))
-           (setq c2 c1))
-         (setq c (or c2 char)))
-       (push (cons k c) new))))
+      (if (or (memq (car e) '(:newline :endgroup :startgroup))
+             (cdr e)) ;; Key already assigned.
+         (push e new)
+       (let ((clist (string-to-list (downcase (car e))))
+             (used (append new alist)))
+         (when (= (car clist) ?@)
+           (pop clist))
+         (while (and clist (rassoc (car clist) used))
+           (pop clist))
+         (unless clist
+           (while (rassoc alt used)
+             (incf alt)))
+         (push (cons (car e) (or (car clist) alt)) new))))
     (nreverse new)))
 
 ;;; Some variables used in various places
 
 (defvar org-window-configuration nil
   "Used in various places to store a window configuration.")
+(defvar org-selected-window nil
+  "Used in various places to store a window configuration.")
 (defvar org-finish-function nil
   "Function to be called when `C-c C-c' is used.
 This is for getting out of special buffers like remember.")
@@ -3892,16 +4608,15 @@ This is for getting out of special buffers like remember.")
 (defvar date)
 
 ;; Defined somewhere in this file, but used before definition.
-(defvar org-html-entities)
+(defvar org-entities)     ;; defined in org-entities.el
 (defvar org-struct-menu)
 (defvar org-org-menu)
 (defvar org-tbl-menu)
-(defvar org-agenda-keymap)
 
 ;;;; Define the Org-mode
 
 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
-    (error "Conflict with outdated version of allout.el.  Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22."))
+    (error "Conflict with outdated version of allout.el.  Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
 
 
 ;; We use a before-change function to check if a table might need
@@ -3914,9 +4629,8 @@ This variable is set by `org-before-change-function'.
   "Every change indicates that a table might need an update."
   (setq org-table-may-need-update t))
 (defvar org-mode-map)
-(defvar org-mode-hook nil
-  "Mode hook for Org-mode, run after the mode was turned on.")
 (defvar org-inhibit-startup nil)        ; Dynamically-scoped param.
+(defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
 (defvar org-agenda-keep-modes nil)      ; Dynamically-scoped param.
 (defvar org-inhibit-logging nil)        ; Dynamically-scoped param.
 (defvar org-inhibit-blocking nil)       ; Dynamically-scoped param.
@@ -3949,7 +4663,7 @@ The following commands are available:
   ;; we switch another buffer into org-mode.
   (if (featurep 'xemacs)
       (when (boundp 'outline-mode-menu-heading)
-       ;; Assume this is Greg's port, it used easymenu
+       ;; Assume this is Greg's port, it uses easymenu
        (easy-menu-remove outline-mode-menu-heading)
        (easy-menu-remove outline-mode-menu-show)
        (easy-menu-remove outline-mode-menu-hide))
@@ -3961,9 +4675,9 @@ The following commands are available:
   (easy-menu-add org-org-menu)
   (easy-menu-add org-tbl-menu)
   (org-install-agenda-files-menu)
-  (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
-  (org-add-to-invisibility-spec '(org-cwidth))
-  (org-add-to-invisibility-spec '(org-hide-block . t))
+  (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
+  (add-to-invisibility-spec '(org-cwidth))
+  (add-to-invisibility-spec '(org-hide-block . t))
   (when (featurep 'xemacs)
     (org-set-local 'line-move-ignore-invisible t))
   (org-set-local 'outline-regexp org-outline-regexp)
@@ -3986,7 +4700,6 @@ The following commands are available:
     (org-set-tag-faces 'org-tag-faces org-tag-faces))
   ;; 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
@@ -4001,6 +4714,9 @@ The following commands are available:
   (org-set-autofill-regexps)
   (setq indent-line-function 'org-indent-line-function)
   (org-update-radio-target-regexp)
+  ;; Beginning/end of defun
+  (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
+  (org-set-local 'end-of-defun-function 'org-end-of-defun)
   ;; Make sure dependence stuff works reliably, even for users who set it
   ;; too late :-(
   (if org-enforce-todo-dependencies
@@ -4015,7 +4731,7 @@ The following commands are available:
                 'org-block-todo-from-checkboxes))
 
   ;; Comment characters
-;  (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
+  (org-set-local 'comment-start "#")
   (org-set-local 'comment-padding " ")
 
   ;; Align options lines
@@ -4038,21 +4754,41 @@ The following commands are available:
     (org-set-local 'outline-isearch-open-invisible-function
                   (lambda (&rest ignore) (org-show-context 'isearch))))
 
+  ;; Turn on org-beamer-mode?
+  (and org-startup-with-beamer-mode (org-beamer-mode 1))
+
+  ;; Setup the pcomplete hooks
+  (set (make-local-variable 'pcomplete-command-completion-function)
+       'org-complete-initial)
+  (set (make-local-variable 'pcomplete-command-name-function)
+       'org-command-at-point)
+  (set (make-local-variable 'pcomplete-default-completion-function)
+       'ignore)
+  (set (make-local-variable 'pcomplete-parse-arguments-function)
+       'org-parse-arguments)
+  (set (make-local-variable 'pcomplete-termination-string) "")
+
   ;; If empty file that did not turn on org-mode automatically, make it to.
   (if (and org-insert-mode-line-in-empty-file
           (interactive-p)
           (= (point-min) (point-max)))
       (insert "#    -*- mode: org -*-\n\n"))
-
   (unless org-inhibit-startup
     (when org-startup-align-all-tables
       (let ((bmp (buffer-modified-p)))
-       (org-table-map-tables 'org-table-align)
+       (org-table-map-tables 'org-table-align 'quietly)
        (set-buffer-modified-p bmp)))
+    (when org-startup-with-inline-images
+      (org-display-inline-images))
     (when org-startup-indented
       (require 'org-indent)
       (org-indent-mode 1))
-    (org-set-startup-visibility)))
+    (unless org-inhibit-startup-visibility-stuff
+      (org-set-startup-visibility))))
+
+(when (fboundp 'abbrev-table-put)
+  (abbrev-table-put org-mode-abbrev-table
+                   :parents (list text-mode-abbrev-table)))
 
 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
 
@@ -4066,13 +4802,17 @@ The following commands are available:
                       (nthcdr 2 time))))
     (current-time)))
 
+(defun org-today ()
+  "Return today date, considering `org-extend-today-until'."
+  (time-to-days
+   (time-subtract (current-time)
+                 (list 0 (* 3600 org-extend-today-until) 0))))
+
 ;;;; Font-Lock stuff, including the activators
 
 (defvar org-mouse-map (make-sparse-keymap))
-(org-defkey org-mouse-map
-  (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
-(org-defkey org-mouse-map
-  (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
+(org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
+(org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
 (when org-mouse-1-follows-link
   (org-defkey org-mouse-map [follow-link] 'mouse-face))
 (when org-tab-follows-link
@@ -4083,7 +4823,7 @@ The following commands are available:
 
 (defconst org-non-link-chars "]\t\n\r<>")
 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
-                          "shell" "elisp"))
+                          "shell" "elisp" "doi" "message"))
 (defvar org-link-types-re nil
    "Matches a link that has a url-like prefix like \"http:\"")
 (defvar org-link-re-with-space nil
@@ -4107,49 +4847,91 @@ Here is what the match groups contain after a match:
 4: [desc]
 5: desc")
 (defvar org-bracket-link-analytic-regexp++ nil
-  "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
+  "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
 (defvar org-any-link-re nil
   "Regular expression matching any link.")
 
+(defcustom org-match-sexp-depth 3
+  "Number of stacked braces for sub/superscript matching.
+This has to be set before loading org.el to be effective."
+  :group 'org-export-translation ; ??????????????????????????/
+  :type 'integer)
+
+(defun org-create-multibrace-regexp (left right n)
+  "Create a regular expression which will match a balanced sexp.
+Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
+as single character strings.
+The regexp returned will match the entire expression including the
+delimiters.  It will also define a single group which contains the
+match except for the outermost delimiters.  The maximum depth of
+stacked delimiters is N.  Escaping delimiters is not possible."
+  (let* ((nothing (concat "[^" left right "]*?"))
+        (or "\\|")
+        (re nothing)
+        (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
+    (while (> n 1)
+      (setq n (1- n)
+           re (concat re or next)
+           next (concat "\\(?:" nothing left next right "\\)+" nothing)))
+    (concat left "\\(" re "\\)" right)))
+
+(defvar org-match-substring-regexp
+  (concat
+   "\\([^\\]\\)\\([_^]\\)\\("
+   "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
+   "\\|"
+   "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
+   "\\|"
+   "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
+  "The regular expression matching a sub- or superscript.")
+
+(defvar org-match-substring-with-braces-regexp
+  (concat
+   "\\([^\\]\\)\\([_^]\\)\\("
+   "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
+   "\\)")
+  "The regular expression matching a sub- or superscript, forcing braces.")
+
 (defun org-make-link-regexps ()
   "Update the link regular expressions.
 This should be called after the variable `org-link-types' has changed."
   (setq org-link-types-re
        (concat
-        "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
+        "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
        org-link-re-with-space
        (concat
-        "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
+        "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
         "\\([^" org-non-link-chars " ]"
         "[^" org-non-link-chars "]*"
         "[^" org-non-link-chars " ]\\)>?")
        org-link-re-with-space2
        (concat
-        "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
+        "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
         "\\([^" org-non-link-chars " ]"
         "[^\t\n\r]*"
         "[^" org-non-link-chars " ]\\)>?")
        org-link-re-with-space3
        (concat
-        "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
+        "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
         "\\([^" org-non-link-chars " ]"
         "[^\t\n\r]*\\)")
        org-angle-link-re
        (concat
-        "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
+        "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
         "\\([^" org-non-link-chars " ]"
         "[^" org-non-link-chars "]*"
         "\\)>")
        org-plain-link-re
        (concat
-        "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
-        "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
+        "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
+        (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
+       ;;       "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
        org-bracket-link-regexp
        "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
        org-bracket-link-analytic-regexp
        (concat
         "\\[\\["
-        "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
+        "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
         "\\([^]]+\\)"
         "\\]"
         "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
@@ -4157,7 +4939,7 @@ This should be called after the variable `org-link-types' has changed."
        org-bracket-link-analytic-regexp++
        (concat
         "\\[\\["
-        "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
+        "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
         "\\([^]]+\\)"
         "\\]"
         "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
@@ -4214,7 +4996,7 @@ The time stamps may be either active or inactive.")
                 (org-remove-flyspell-overlays-in
                  (match-beginning 0) (match-end 0)))
            (add-text-properties (match-beginning 2) (match-end 2)
-                                '(font-lock-multiline t))
+                                '(font-lock-multiline t org-emphasis t))
            (when org-hide-emphasis-markers
              (add-text-properties (match-end 4) (match-beginning 5)
                                   '(invisible org-link))
@@ -4269,8 +5051,9 @@ will be prompted for."
                (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))))
+    (unless (or (eobp)
+               (string-match (concat "[" (nth 1 erc) "\n]")
+                             (char-to-string (char-after (point)))))
       (insert " ") (backward-char 1))
     (insert string)
     (and move (backward-char 1))))
@@ -4294,6 +5077,7 @@ will be prompted for."
                nil
              (add-text-properties (match-beginning 0) (match-end 0)
                                   (list 'mouse-face 'highlight
+                                        'face 'org-link
                                         'keymap org-mouse-map))
              (org-rear-nonsticky-at (match-end 0)))
            t)))))
@@ -4306,17 +5090,26 @@ will be prompted for."
                                '(display t invisible t intangible t))
        t)))
 
+(defcustom org-src-fontify-natively nil
+  "When non-nil, fontify code in code blocks."
+  :type 'boolean
+  :group 'org-appearance
+  :group 'org-babel)
+
 (defun org-fontify-meta-lines-and-blocks (limit)
   "Fontify #+ lines and blocks, in the correct ways."
   (let ((case-fold-search t))
     (if (re-search-forward
-        "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
+        "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
         limit t)
        (let ((beg (match-beginning 0))
+             (block-start (match-end 0))
+             (block-end nil)
+             (lang (match-string 7))
              (beg1 (line-beginning-position 2))
              (dc1 (downcase (match-string 2)))
              (dc3 (downcase (match-string 3)))
-             end end1 quoting)
+             end end1 quoting block-type)
          (cond
           ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
            ;; a single line of backend-specific content
@@ -4325,17 +5118,19 @@ will be prompted for."
                                    '(display t invisible t intangible t))
            (add-text-properties (match-beginning 1) (match-end 3)
                                 '(font-lock-fontified t face org-meta-line))
-           (add-text-properties (match-beginning 6) (match-end 6)
+           (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
                                 '(font-lock-fontified t face org-block))
+                                       ; for backend-specific code
            t)
           ((and (match-end 4) (equal dc3 "begin"))
-           ;; Truely a block
-           (setq quoting (member (downcase (match-string 5))
-                                 org-protecting-blocks))
+           ;; Truly a block
+           (setq block-type (downcase (match-string 5))
+                 quoting (member block-type org-protecting-blocks))
            (when (re-search-forward
                   (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
                   nil t)  ;; on purpose, we look further than LIMIT
              (setq end (match-end 0) end1 (1- (match-beginning 0)))
+             (setq block-end (match-beginning 0))
              (when quoting
                (remove-text-properties beg end
                                        '(display t invisible t intangible t)))
@@ -4343,22 +5138,50 @@ will be prompted for."
               beg end
               '(font-lock-fontified t font-lock-multiline t))
              (add-text-properties beg beg1 '(face org-meta-line))
-             (add-text-properties end1 end '(face org-meta-line))
-             (when quoting
-               (add-text-properties beg1 end1 '(face org-block)))
+             (add-text-properties end1 (+ end 1) '(face org-meta-line))
+                                       ; for end_src
+             (cond
+              ((and lang org-src-fontify-natively)
+               (org-src-font-lock-fontify-block lang block-start block-end))
+              (quoting
+               (add-text-properties beg1 (+ end1 1) '(face
+                                                      org-block)))
+                                       ; end of source block
+              ((not org-fontify-quote-and-verse-blocks))
+              ((string= block-type "quote")
+               (add-text-properties beg1 end1 '(face org-quote)))
+              ((string= block-type "verse")
+               (add-text-properties beg1 end1 '(face org-verse))))
              t))
+          ((member dc1 '("title:" "author:" "email:" "date:"))
+           (add-text-properties
+            beg (match-end 3)
+            (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
+                '(font-lock-fontified t invisible t)
+              '(font-lock-fontified t face org-document-info-keyword)))
+           (add-text-properties
+            (match-beginning 6) (match-end 6)
+            (if (string-equal dc1 "title:")
+                '(font-lock-fontified t face org-document-title)
+              '(font-lock-fontified t face org-document-info))))
           ((not (member (char-after beg) '(?\  ?\t)))
            ;; just any other in-buffer setting, but not indented
            (add-text-properties
             beg (match-end 0)
             '(font-lock-fontified t face org-meta-line))
            t)
-          ((or (member dc1 '("caption:" "label:" "orgtbl:" "tblfm:" "tblname:"))
+          ((or (member dc1 '("begin:" "end:" "caption:" "label:"
+                             "orgtbl:" "tblfm:" "tblname:" "result:"
+                             "results:" "source:" "srcname:" "call:"))
                (and (match-end 4) (equal dc3 "attr")))
            (add-text-properties
             beg (match-end 0)
             '(font-lock-fontified t face org-meta-line))
            t)
+          ((member dc3 '(" " ""))
+           (add-text-properties
+            beg (match-end 0)
+            '(font-lock-fontified t face font-lock-comment-face)))
           (t nil))))))
 
 (defun org-activate-angle-links (limit)
@@ -4505,6 +5328,7 @@ will be prompted for."
        ((matchers (plist-get org-format-latex-options :matchers))
         (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
                                   org-latex-regexps)))
+        (org-export-allow-BIND nil)
         (options (org-combine-plists (org-default-export-plist)
                                      (org-infile-export-plist)))
         (org-export-with-sub-superscripts (plist-get options :sub-superscript))
@@ -4526,12 +5350,17 @@ will be prompted for."
          (if org-export-with-TeX-macros
              (list (concat "\\\\"
                            (regexp-opt
-                            (append (mapcar 'car org-html-entities)
-                                    (if (boundp 'org-latex-entities)
-                                        (mapcar (lambda (x)
-                                                  (or (car-safe x) x))
-                                                org-latex-entities)
-                                      nil))
+                            (append
+
+                             (delq nil
+                                   (mapcar 'car-safe
+                                           (append org-entities-user
+                                                   org-entities)))
+                             (if (boundp 'org-latex-entities)
+                                 (mapcar (lambda (x)
+                                           (or (car-safe x) x))
+                                         org-latex-entities)
+                               nil))
                             'words))) ; FIXME
            ))
     ;;                 (list "\\\\\\(?:[a-zA-Z]+\\)")))
@@ -4570,7 +5399,7 @@ will be prompted for."
       rtn)))
 
 (defun org-restart-font-lock ()
-  "Restart font-lock-mode, to force refontification."
+  "Restart `font-lock-mode', to force refontification."
   (when (and (boundp 'font-lock-mode) font-lock-mode)
     (font-lock-mode -1)
     (font-lock-mode 1)))
@@ -4603,9 +5432,9 @@ between words."
        "\\)\\>")))
 
 (defun org-activate-tags (limit)
-  (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
+  (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
       (progn
-       (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
+       (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
        (add-text-properties (match-beginning 1) (match-end 1)
                             (list 'mouse-face 'highlight
                                   'keymap org-mouse-map))
@@ -4613,6 +5442,13 @@ between words."
        t)))
 
 (defun org-outline-level ()
+  "Compute the outline level of the heading at point.
+This function assumes that the cursor is at the beginning of a line matched
+by `outline-regexp'.  Otherwise it returns garbage.
+If this is called at a normal headline, the level is the number of stars.
+Use `org-reduced-level' to remove the effect of `org-odd-levels'.
+For plain list items, if they are matched by `outline-regexp', this returns
+1000 plus the line indentation."
   (save-excursion
     (looking-at outline-regexp)
     (if (match-beginning 1)
@@ -4627,6 +5463,12 @@ between words."
 (defvar org-font-lock-hook nil
   "Functions to be called for special font lock stuff.")
 
+(defvar org-font-lock-set-keywords-hook nil
+  "Functions that can manipulate `org-font-lock-extra-keywords'.
+This is calles after `org-font-lock-extra-keywords' is defined, but before
+it is installed to be used by font lock.  This can be useful if something
+needs to be inserted at a specific position in the font-lock sequence.")
+
 (defun org-font-lock-hook (limit)
   (run-hook-with-args 'org-font-lock-hook limit))
 
@@ -4651,7 +5493,7 @@ between words."
           '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
           '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
           '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
-          '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
+          '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
           ;; Drawers
           (list org-drawer-regexp '(0 'org-special-keyword t))
           (list "^[ \t]*:END:" '(0 'org-special-keyword t))
@@ -4662,7 +5504,7 @@ between words."
           ;; 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 'plain lk) '(org-activate-plain-links))
           (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)))
@@ -4695,19 +5537,21 @@ between words."
                    '(org-do-emphasis-faces (0 nil append))
                  '(org-do-emphasis-faces)))
           ;; Checkboxes
-          '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
-            2 'org-checkbox prepend)
-          (if org-provide-checkbox-statistics
+          '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
+            1 'org-checkbox prepend)
+          (if (cdr (assq 'checkbox org-list-automatic-rules))
               '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
                 (0 (org-get-checkbox-statistics-face) t)))
           ;; Description list items
-          '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
+          '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\(.*? ::\\)"
             2 'bold prepend)
           ;; ARCHIVEd headings
           (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
                 '(1 'org-archived prepend))
           ;; Specials
           '(org-do-latex-and-special-faces)
+          '(org-fontify-entities)
+          '(org-raise-scripts)
           ;; Code
           '(org-activate-code (1 'org-code t))
           ;; COMMENT
@@ -4719,14 +5563,48 @@ between words."
           '(org-fontify-meta-lines-and-blocks)
           )))
     (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
+    (run-hooks 'org-font-lock-set-keywords-hook)
     ;; Now set the full font-lock-keywords
     (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
     (org-set-local 'font-lock-defaults
                   '(org-font-lock-keywords t nil nil backward-paragraph))
     (kill-local-variable 'font-lock-keywords) nil))
 
+(defun org-toggle-pretty-entities ()
+  "Toggle the composition display of entities as UTF8 characters."
+  (interactive)
+  (org-set-local 'org-pretty-entities (not org-pretty-entities))
+  (org-restart-font-lock)
+  (if org-pretty-entities
+      (message "Entities are displayed as UTF8 characers")
+    (save-restriction
+      (widen)
+      (org-decompose-region (point-min) (point-max))
+      (message "Entities are displayed plain"))))
+
+(defun org-fontify-entities (limit)
+  "Find an entity to fontify."
+  (let (ee)
+    (when org-pretty-entities
+      (catch 'match
+       (while (re-search-forward
+               "\\\\\\([a-zA-Z][a-zA-Z0-9]*\\)\\($\\|[^[:alnum:]\n]\\)"
+               limit t)
+         (if (and (not (org-in-indented-comment-line))
+                  (setq ee (org-entity-get (match-string 1)))
+                  (= (length (nth 6 ee)) 1))
+             (progn
+               (add-text-properties
+                (match-beginning 0) (match-end 1)
+                (list 'font-lock-fontified t))
+               (compose-region (match-beginning 0) (match-end 1)
+                               (nth 6 ee) nil)
+               (backward-char 1)
+               (throw 'match t))))
+       nil))))
+
 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
-  "Fontify string S like in Org-mode"
+  "Fontify string S like in Org-mode."
   (with-temp-buffer
     (insert s)
     (let ((org-odd-levels-only odd-levels))
@@ -4738,23 +5616,36 @@ between words."
 (defvar org-l nil)
 (defvar org-f nil)
 (defun org-get-level-face (n)
-  "Get the right face for match N in font-lock matching of headlines."
-  (setq org-l (- (match-end 2) (match-beginning 1) 1))
-  (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
-  (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
-  (cond
-   ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
-   ((eq n 2) org-f)
-   (t (if org-level-color-stars-only nil org-f))))
+ "Get the right face for match N in font-lock matching of headlines."
+ (setq org-l (- (match-end 2) (match-beginning 1) 1))
+ (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
+ (if org-cycle-level-faces
+     (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
+   (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
+ (cond
+  ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
+  ((eq n 2) org-f)
+  (t (if org-level-color-stars-only nil org-f))))
+
 
 (defun org-get-todo-face (kwd)
   "Get the right face for a TODO keyword KWD.
 If KWD is a number, get the corresponding match group."
   (if (numberp kwd) (setq kwd (match-string kwd)))
-  (or (cdr (assoc kwd org-todo-keyword-faces))
+  (or (org-face-from-face-or-color
+       'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
       (and (member kwd org-done-keywords) 'org-done)
       'org-todo))
 
+(defun org-face-from-face-or-color (context inherit face-or-color)
+  "Create a face list that inherits INHERIT, but sets the foreground color.
+When FACE-OR-COLOR is not a string, just return it."
+  (if (stringp face-or-color)
+      (list :inherit inherit
+           (cdr (assoc context org-faces-easy-properties))
+           face-or-color)
+    face-or-color))
+
 (defun org-font-lock-add-tag-faces (limit)
   "Add the special tag faces."
   (when (and org-tag-faces org-tags-special-faces-re)
@@ -4769,8 +5660,10 @@ If KWD is a number, get the corresponding match group."
   (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
     (add-text-properties
      (match-beginning 0) (match-end 0)
-     (list 'face (or (cdr (assoc (char-after (match-beginning 1))
-                                org-priority-faces))
+     (list 'face (or (org-face-from-face-or-color
+                     'priority 'org-special-keyword
+                     (cdr (assoc (char-after (match-beginning 1))
+                                 org-priority-faces)))
                     'org-special-keyword)
           'font-lock-fontified t))))
 
@@ -4778,7 +5671,8 @@ If KWD is a number, get the corresponding match group."
   "Get the right face for a TODO keyword KWD.
 If KWD is a number, get the corresponding match group."
   (if (numberp kwd) (setq kwd (match-string kwd)))
-  (or (cdr (assoc kwd org-tag-faces))
+  (or (org-face-from-face-or-color
+       'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
       'org-tag))
 
 (defun org-unfontify-region (beg end &optional maybe_loudly)
@@ -4788,11 +5682,77 @@ If KWD is a number, get the corresponding match group."
         (inhibit-read-only t) (inhibit-point-motion-hooks t)
         (inhibit-modification-hooks t)
         deactivate-mark buffer-file-name buffer-file-truename)
-    (remove-text-properties beg end
-                           '(mouse-face t keymap t org-linked-text t
-                                        invisible t intangible t
-                                        line-prefix t wrap-prefix t
-                                        org-no-flyspell t))))
+    (org-decompose-region beg end)
+    (remove-text-properties
+     beg end
+     (if org-indent-mode
+        ;; also remove line-prefix and wrap-prefix properties
+        '(mouse-face t keymap t org-linked-text t
+                     invisible t intangible t
+                     line-prefix t wrap-prefix t
+                     org-no-flyspell t org-emphasis t)
+       '(mouse-face t keymap t org-linked-text t
+                   invisible t intangible t
+                   org-no-flyspell t org-emphasis t)))
+    (org-remove-font-lock-display-properties beg end)))
+
+(defconst org-script-display  '(((raise -0.3) (height 0.7))
+                               ((raise 0.3)  (height 0.7))
+                               ((raise -0.5))
+                               ((raise 0.5)))
+  "Display properties for showing superscripts and subscripts.")
+
+(defun org-remove-font-lock-display-properties (beg end)
+  "Remove specific display properties that have been added by font lock.
+The will remove the raise properties that are used to show superscripts
+and subscripts."
+  (let (next prop)
+    (while (< beg end)
+      (setq next (next-single-property-change beg 'display nil end)
+           prop (get-text-property beg 'display))
+      (if (member prop org-script-display)
+         (put-text-property beg next 'display nil))
+      (setq beg next))))
+
+(defun org-raise-scripts (limit)
+  "Add raise properties to sub/superscripts."
+  (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
+    (if (re-search-forward
+        (if (eq org-use-sub-superscripts t)
+            org-match-substring-regexp
+          org-match-substring-with-braces-regexp)
+        limit t)
+       (let* ((pos (point)) table-p comment-p
+              (mpos (match-beginning 3))
+              (emph-p (get-text-property mpos 'org-emphasis))
+              (link-p (get-text-property mpos 'mouse-face))
+              (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
+         (goto-char (point-at-bol))
+         (setq table-p (org-looking-at-p org-table-dataline-regexp)
+               comment-p (org-looking-at-p "[ \t]*#"))
+         (goto-char pos)
+         ;; FIXME: Should we go back one character here, for a_b^c
+         ;; (goto-char (1- pos)) ;????????????????????
+         (if (or comment-p emph-p link-p keyw-p)
+             t
+           (put-text-property (match-beginning 3) (match-end 0)
+                              'display
+                              (if (equal (char-after (match-beginning 2)) ?^)
+                                  (nth (if table-p 3 1) org-script-display)
+                                (nth (if table-p 2 0) org-script-display)))
+           (add-text-properties (match-beginning 2) (match-end 2)
+                                (list 'invisible t
+                                      'org-dwidth t 'org-dwidth-n 1))
+           (if (and (eq (char-after (match-beginning 3)) ?{)
+                    (eq (char-before (match-end 3)) ?}))
+               (progn
+                 (add-text-properties
+                  (match-beginning 3) (1+ (match-beginning 3))
+                  (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
+                 (add-text-properties
+                  (1- (match-end 3)) (match-end 3)
+                  (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
+           t)))))
 
 ;;;; Visibility cycling, including org-goto and indirect buffer
 
@@ -4811,7 +5771,7 @@ If KWD is a number, get the corresponding match group."
   "TAB-action and visibility cycling for Org-mode.
 
 This is the command invoked in Org-mode by the TAB key.  Its main purpose
-is outine visibility cycling, but it also invokes other actions
+is outline visibility cycling, but it also invokes other actions
 in special contexts.
 
 - When this function is called with a prefix argument, rotate the entire
@@ -4836,6 +5796,12 @@ in special contexts.
   3. SUBTREE:  Show the entire subtree, including body text.
   If there is no subtree, switch directly from CHILDREN to FOLDED.
 
+- When point is at the beginning of an empty headline and the variable
+  `org-cycle-level-after-item/entry-creation' is set, cycle the level
+  of the headline by demoting and promoting it to likely levels.  This
+  speeds up creation document structure by pressing TAB once or several
+  times right after creating a new headline.
+
 - When there is a numeric prefix, go up to a heading with level ARG, do
   a `show-subtree' and return to the previous cursor position.  If ARG
   is negative, go up that many levels.
@@ -4845,11 +5811,15 @@ in special contexts.
   `org-cycle-emulate-tab' for details.
 
 - Special case: if point is at the beginning of the buffer and there is
-  no headline in line 1, this function will act as if called with prefix arg.
+  no headline in line 1, this function will act as if called with prefix arg
+  (C-u TAB, same as S-TAB) also when called without prefix arg.
   But only if also the variable `org-cycle-global-at-bob' is t."
   (interactive "P")
   (org-load-modules-maybe)
-  (unless (run-hook-with-args-until-success 'org-tab-first-hook)
+  (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
+             (and org-cycle-level-after-item/entry-creation
+                  (or (org-cycle-level)
+                      (org-cycle-item-indentation))))
     (let* ((limit-level
            (or org-cycle-max-level
                (and (boundp 'org-inlinetask-min-level)
@@ -4868,7 +5838,7 @@ in special contexts.
                      (if nstars (format "\\{1,%d\\}" nstars) "+")
                      " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
             (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
-          (bob-special (and org-cycle-global-at-bob (bobp)
+          (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
                             (not (looking-at outline-regexp))))
           (org-cycle-hook
            (if bob-special
@@ -4884,6 +5854,7 @@ in special contexts.
       (cond
 
        ((equal arg '(16))
+       (setq last-command 'dummy)
        (org-set-startup-visibility)
        (message "Startup visibility, plus VISIBILITY properties"))
 
@@ -4893,11 +5864,11 @@ in special contexts.
 
        ((org-at-table-p 'any)
        ;; Enter the table or move to the next field in the table
-       (or (org-table-recognize-table.el)
-           (progn
-             (if arg (org-table-edit-field t)
-               (org-table-justify-field-maybe)
-               (call-interactively 'org-table-next-field)))))
+       (if (org-at-table.el-p)
+           (message "Use C-c ' to edit table.el tables")
+         (if arg (org-table-edit-field t)
+           (org-table-justify-field-maybe)
+           (call-interactively 'org-table-next-field))))
 
        ((run-hook-with-args-until-success
         'org-tab-after-check-for-table-hook))
@@ -4936,6 +5907,9 @@ in special contexts.
 
        ((org-try-cdlatex-tab))
 
+       ((run-hook-with-args-until-success
+        'org-tab-before-tab-emulation-hook))
+
        ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
             (or (not (bolp))
                 (not (looking-at outline-regexp))))
@@ -4988,7 +5962,6 @@ in special contexts.
 
 (defun org-cycle-internal-local ()
   "Do the local cycling action."
-  (org-back-to-heading)
   (let ((goal-column 0) eoh eol eos level has-children children-skipped)
     ;; First, some boundaries
     (save-excursion
@@ -5005,7 +5978,6 @@ in special contexts.
          (while (and (not (eobp)) ;; this is like `next-line'
                      (get-char-property (1- (point)) 'invisible))
            (goto-char (next-single-char-property-change (point) 'invisible))
-;;;???     (or (bolp) (beginning-of-line 2))))
            (and (eolp) (beginning-of-line 2))))
        (setq eol (point)))
       (outline-end-of-heading)   (setq eoh (point))
@@ -5013,12 +5985,15 @@ in special contexts.
        (outline-next-heading)
        (setq has-children (and (org-at-heading-p t)
                                (> (funcall outline-level) level))))
-      (org-end-of-subtree t)
-      (unless (eobp)
-       (skip-chars-forward " \t\n")
-       (beginning-of-line 1) ; in case this is an item
-       )
-      (setq eos (if (eobp) (point) (1- (point)))))
+      ;; if we're in a list, org-end-of-subtree is in fact org-end-of-item.
+      (if (org-at-item-p)
+         (setq eos (if (and (org-end-of-item) (bolp))
+                       (1- (point))
+                     (point)))
+       (org-end-of-subtree t)
+       (unless (eobp)
+         (skip-chars-forward " \t\n"))
+       (setq eos (if (eobp) (point) (1- (point))))))
     ;; Find out what to do next and set `this-command'
     (cond
      ((= eos eoh)
@@ -5052,14 +6027,14 @@ in special contexts.
       ;; We just showed the children, or no children are there,
       ;; now show everything.
       (run-hook-with-args 'org-pre-cycle-hook 'subtree)
-      (org-show-subtree)
+      (outline-flag-region eoh eos nil)
       (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
       (setq org-cycle-subtree-status 'subtree)
       (run-hook-with-args 'org-cycle-hook 'subtree))
      (t
       ;; Default action: hide the subtree.
       (run-hook-with-args 'org-pre-cycle-hook 'folded)
-      (hide-subtree)
+      (outline-flag-region eoh eos t)
       (message "FOLDED")
       (setq org-cycle-subtree-status 'folded)
       (run-hook-with-args 'org-cycle-hook 'folded)))))
@@ -5067,7 +6042,7 @@ in special contexts.
 ;;;###autoload
 (defun org-global-cycle (&optional arg)
   "Cycle the global visibility.  For details see `org-cycle'.
-With C-u prefix arg, switch to startup visibility.
+With \\[universal-argument] prefix arg, switch to startup visibility.
 With a numeric prefix, show all headlines up to that level."
   (interactive "P")
   (let ((org-cycle-include-plain-lists
@@ -5091,11 +6066,12 @@ With a numeric prefix, show all headlines up to that level."
    ((eq org-startup-folded 'content)
     (let ((this-command 'org-cycle) (last-command 'org-cycle))
       (org-cycle '(4)) (org-cycle '(4)))))
-  (if org-hide-block-startup (org-hide-block-all))
-  (org-set-visibility-according-to-property 'no-cleanup)
-  (org-cycle-hide-archived-subtrees 'all)
-  (org-cycle-hide-drawers 'all)
-  (org-cycle-show-empty-lines 'all))
+  (unless (eq org-startup-folded 'showeverything)
+    (if org-hide-block-startup (org-hide-block-all))
+    (org-set-visibility-according-to-property 'no-cleanup)
+    (org-cycle-hide-archived-subtrees 'all)
+    (org-cycle-hide-drawers 'all)
+    (org-cycle-show-empty-lines t)))
 
 (defun org-set-visibility-according-to-property (&optional no-cleanup)
   "Switch subtree visibilities according to :VISIBILITY: property."
@@ -5175,28 +6151,15 @@ This function is the default value of the hook `org-cycle-hook'."
      ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
      ((eq state 'subtree)  (or (org-subtree-end-visible-p) (recenter 1))))))
 
-;; FIXME: no longer in use
-(defun org-compact-display-after-subtree-move ()
-  "Show a compacter version of the tree of the entry's parent."
-  (save-excursion
-    (if (org-up-heading-safe)
-       (progn
-         (hide-subtree)
-         (show-entry)
-         (show-children)
-         (org-cycle-show-empty-lines 'children)
-         (org-cycle-hide-drawers 'children))
-      (org-overview))))
-
 (defun org-remove-empty-overlays-at (pos)
   "Remove outline overlays that do not contain non-white stuff."
   (mapc
    (lambda (o)
-     (and (eq 'outline (org-overlay-get o 'invisible))
-         (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
-                                                       (org-overlay-end o))))
-         (org-delete-overlay o)))
-   (org-overlays-at pos)))
+     (and (eq 'outline (overlay-get o 'invisible))
+         (not (string-match "\\S-" (buffer-substring (overlay-start o)
+                                                     (overlay-end o))))
+         (delete-overlay o)))
+   (overlays-at pos)))
 
 (defun org-clean-visibility-after-subtree-move ()
   "Fix visibility issues after moving a subtree."
@@ -5222,7 +6185,9 @@ This function is the default value of the hook `org-cycle-hook'."
          ;; Properly fold already folded siblings
          (goto-char (point-min))
          (while (re-search-forward re nil t)
-           (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
+           (if (and (not (org-invisible-p))
+                    (save-excursion
+                      (goto-char (point-at-eol)) (org-invisible-p)))
                (hide-entry))))
        (org-cycle-show-empty-lines 'overview)
        (org-cycle-hide-drawers 'overview)))))
@@ -5259,7 +6224,11 @@ are at least `org-cycle-separator-lines' empty lines before the headline."
                  (setq b (save-excursion
                            (goto-char (match-beginning 0))
                            (org-back-over-empty-lines)
-                           (point)))
+                           (if (save-excursion
+                                 (goto-char (max (point-min) (1- (point))))
+                                 (org-on-heading-p))
+                               (1- (point))
+                             (point))))
                (setq b (match-beginning 1)))
              (outline-flag-region b e nil)))))))
   ;; Never hide empty lines at the end of the file.
@@ -5277,6 +6246,27 @@ are at least `org-cycle-separator-lines' empty lines before the headline."
     (let ((context (if (org-up-heading-safe) 'children 'overview)))
       (org-cycle-show-empty-lines context))))
 
+(defun org-files-list ()
+  "Return `org-agenda-files' list, plus all open org-mode files.
+This is useful for operations that need to scan all of a user's
+open and agenda-wise Org files."
+  (let ((files (mapcar 'expand-file-name (org-agenda-files))))
+    (dolist (buf (buffer-list))
+      (with-current-buffer buf
+       (if (and (eq major-mode 'org-mode) (buffer-file-name))
+           (let ((file (expand-file-name (buffer-file-name))))
+             (unless (member file files)
+               (push file files))))))
+    files))
+
+(defsubst org-entry-beginning-position ()
+  "Return the beginning position of the current entry."
+  (save-excursion (outline-back-to-heading t) (point)))
+
+(defsubst org-entry-end-position ()
+  "Return the end position of the current entry."
+  (save-excursion (outline-next-heading) (point)))
+
 (defun org-cycle-hide-drawers (state)
   "Re-hide all drawers after a visibility state change."
   (when (and (org-mode-p)
@@ -5311,12 +6301,49 @@ are at least `org-cycle-separator-lines' empty lines before the headline."
 
 (defun org-first-headline-recenter (&optional N)
   "Move cursor to the first headline and recenter the headline.
-Optional argument N means, put the headline into the Nth line of the window."
+Optional argument N means put the headline into the Nth line of the window."
   (goto-char (point-min))
   (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
     (beginning-of-line)
     (recenter (prefix-numeric-value N))))
 
+;;; Saving and restoring visibility
+
+(defun org-outline-overlay-data (&optional use-markers)
+  "Return a list of the locations of all outline overlays.
+These are overlays with the `invisible' property value `outline'.
+The return value is a list of cons cells, with start and stop
+positions for each overlay.
+If USE-MARKERS is set, return the positions as markers."
+  (let (beg end)
+    (save-excursion
+      (save-restriction
+       (widen)
+       (delq nil
+             (mapcar (lambda (o)
+                       (when (eq (overlay-get o 'invisible) 'outline)
+                         (setq beg (overlay-start o)
+                               end (overlay-end o))
+                         (and beg end (> end beg)
+                              (if use-markers
+                                  (cons (move-marker (make-marker) beg)
+                                        (move-marker (make-marker) end))
+                                (cons beg end)))))
+                     (overlays-in (point-min) (point-max))))))))
+
+(defun org-set-outline-overlay-data (data)
+  "Create visibility overlays for all positions in DATA.
+DATA should have been made by `org-outline-overlay-data'."
+  (let (o)
+    (save-excursion
+      (save-restriction
+       (widen)
+       (show-all)
+       (mapc (lambda (c)
+               (setq o (make-overlay (car c) (cdr c)))
+               (overlay-put o 'invisible 'outline))
+             data)))))
+
 ;;; Folding of blocks
 
 (defconst org-block-regexp
@@ -5325,13 +6352,12 @@ Optional argument N means, put the headline into the Nth line of the window."
   "Regular expression for hiding blocks.")
 
 (defvar org-hide-block-overlays nil
-  "Overays hiding blocks.")
+  "Overlays hiding blocks.")
 (make-variable-buffer-local 'org-hide-block-overlays)
 
 (defun org-block-map (function &optional start end)
-  "Call func at the head of all source blocks in the current
-buffer.  Optional arguments START and END can be used to limit
-the range."
+  "Call FUNCTION at the head of all source blocks in the current buffer.
+Optional arguments START and END can be used to limit the range."
   (let ((start (or start (point-min)))
         (end (or end (point-max))))
     (save-excursion
@@ -5354,7 +6380,8 @@ the range."
 
 (defun org-show-block-all ()
   "Unfold all blocks in the current buffer."
-  (mapc 'org-delete-overlay org-hide-block-overlays)
+  (interactive)
+  (mapc 'delete-overlay org-hide-block-overlays)
   (setq org-hide-block-overlays nil))
 
 (defun org-hide-block-toggle-maybe ()
@@ -5378,30 +6405,30 @@ the range."
               (end (match-end 0)) ;; end of entire body
               ov)
           (if (memq t (mapcar (lambda (overlay)
-                                (eq (org-overlay-get overlay 'invisible)
+                                (eq (overlay-get overlay 'invisible)
                                    'org-hide-block))
-                              (org-overlays-at start)))
+                              (overlays-at start)))
               (if (or (not force) (eq force 'off))
                   (mapc (lambda (ov)
                           (when (member ov org-hide-block-overlays)
                             (setq org-hide-block-overlays
                                   (delq ov org-hide-block-overlays)))
-                          (when (eq (org-overlay-get ov 'invisible)
+                          (when (eq (overlay-get ov 'invisible)
                                     'org-hide-block)
-                            (org-delete-overlay ov)))
-                        (org-overlays-at start)))
-            (setq ov (org-make-overlay start end))
-            (org-overlay-put ov 'invisible 'org-hide-block)
+                            (delete-overlay ov)))
+                        (overlays-at start)))
+            (setq ov (make-overlay start end))
+            (overlay-put ov 'invisible 'org-hide-block)
             ;; make the block accessible to isearch
-            (org-overlay-put
+            (overlay-put
              ov 'isearch-open-invisible
              (lambda (ov)
                (when (member ov org-hide-block-overlays)
                  (setq org-hide-block-overlays
                        (delq ov org-hide-block-overlays)))
-               (when (eq (org-overlay-get ov 'invisible)
+               (when (eq (overlay-get ov 'invisible)
                          'org-hide-block)
-                 (org-delete-overlay ov))))
+                 (delete-overlay ov))))
             (push ov org-hide-block-overlays)))
       (error "Not looking at a source block"))))
 
@@ -5456,7 +6483,7 @@ RET=jump to location             [Q]uit and return to previous location
 
 (defvar org-goto-start-pos) ; dynamically scoped parameter
 
-;; FIXME: Docstring doe not mention both interfaces
+;; FIXME: Docstring does not mention both interfaces
 (defun org-goto (&optional alternative-interface)
   "Look up a different location in the current file, keeping current visibility.
 
@@ -5486,7 +6513,9 @@ the headline hierarchy above."
         (selected-point
          (if (eq interface 'outline)
              (car (org-get-location (current-buffer) org-goto-help))
-           (nth 3 (org-refile-get-location "Goto: ")))))
+           (let ((pa (org-refile-get-location "Goto: ")))
+             (org-refile-check-position pa)
+             (nth 3 pa)))))
     (if selected-point
        (progn
          (org-mark-ring-push org-goto-start-pos)
@@ -5507,7 +6536,11 @@ or nil."
        (isearch-hide-immediately nil)
        (isearch-search-fun-function
         (lambda () 'org-goto-local-search-headings))
-       (org-goto-selected-point org-goto-exit-command))
+       (org-goto-selected-point org-goto-exit-command)
+       (pop-up-frames nil)
+       (special-display-buffer-names nil)
+       (special-display-regexps nil)
+       (special-display-function nil))
     (save-excursion
       (save-window-excursion
        (delete-other-windows)
@@ -5614,10 +6647,12 @@ With numerical prefix ARG, go up to this level and then take that tree.
 If ARG is negative, go up that many levels.
 If `org-indirect-buffer-display' is not `new-frame', the command removes the
 indirect buffer previously made with this command, to avoid proliferation of
-indirect buffers.  However, when you call the command with a `C-u' prefix, or
+indirect buffers.  However, when you call the command with a \
+\\[universal-argument] prefix, or
 when `org-indirect-buffer-display' is `new-frame', the last buffer
 is kept so that you can work with several indirect buffers at the same time.
-If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
+If `org-indirect-buffer-display' is `dedicated-frame', the \
+\\[universal-argument] prefix also
 requests that a new frame be made for the new buffer, so that the dedicated
 frame is not changed."
   (interactive "P")
@@ -5634,7 +6669,9 @@ frame is not changed."
          (outline-up-heading 1 t)))
       (setq beg (point)
            heading (org-get-heading))
-      (org-end-of-subtree t) (setq end (point)))
+      (org-end-of-subtree t t)
+      (if (org-on-heading-p) (backward-char 1))
+      (setq end (point)))
     (if (and (buffer-live-p org-last-indirect-buffer)
             (not (eq org-indirect-buffer-display 'new-frame))
             (not arg))
@@ -5661,7 +6698,7 @@ frame is not changed."
       (switch-to-buffer ibuf))
      ((eq org-indirect-buffer-display 'other-window)
       (pop-to-buffer ibuf))
-     (t (error "Invalid value.")))
+     (t (error "Invalid value")))
     (if (featurep 'xemacs)
         (save-excursion (org-mode) (turn-on-font-lock)))
     (narrow-to-region beg end)
@@ -5696,21 +6733,44 @@ frame is not changed."
         (save-match-data
           (looking-at "[ \t]*$")))))
 
-(defun org-insert-heading (&optional force-heading)
+(defun org-insert-heading (&optional force-heading invisible-ok)
   "Insert a new heading or item with same depth at point.
 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
 If point is at the beginning of a headline, insert a sibling before the
-current headline.  If point is not at the beginning, do not split the line,
-but create the new headline after the current line."
+current headline.  If point is not at the beginning, split the line,
+create the new headline with the text in the current line after point
+\(but see also the variable `org-M-RET-may-split-line').
+
+When INVISIBLE-OK is set, stop at invisible headlines when going back.
+This is important for non-interactive uses of the command."
   (interactive "P")
-  (if (= (buffer-size) 0)
-      (insert "\n* ")
+  (if (or (= (buffer-size) 0)
+         (and (not (save-excursion
+                     (and (ignore-errors (org-back-to-heading invisible-ok))
+                          (org-on-heading-p))))
+              (not (org-in-item-p))))
+      (progn
+       (insert "\n* ")
+       (run-hooks 'org-insert-heading-hook))
     (when (or force-heading (not (org-insert-item)))
       (let* ((empty-line-p nil)
+            (level nil)
+            (on-heading (org-on-heading-p))
             (head (save-excursion
                     (condition-case nil
                         (progn
-                          (org-back-to-heading)
+                          (org-back-to-heading invisible-ok)
+                          (when (and (not on-heading)
+                                     (featurep 'org-inlinetask)
+                                     (integerp org-inlinetask-min-level)
+                                     (>= (length (match-string 0))
+                                         org-inlinetask-min-level))
+                            ;; Find a heading level before the inline task
+                            (while (and (setq level (org-up-heading-safe))
+                                        (>= level org-inlinetask-min-level)))
+                            (if (org-on-heading-p)
+                                (org-back-to-heading invisible-ok)
+                              (error "This should not happen")))
                           (setq empty-line-p (org-previous-line-empty-p))
                           (match-string 0))
                       (error "*"))))
@@ -5748,6 +6808,12 @@ but create the new headline after the current line."
            (cond
             (org-insert-heading-respect-content
              (org-end-of-subtree nil t)
+             (when (featurep 'org-inlinetask)
+               (while (and (not (eobp))
+                           (looking-at "\\(\\*+\\)[ \t]+")
+                           (>= (length (match-string 1))
+                               org-inlinetask-min-level))
+                 (org-end-of-subtree nil t)))
              (or (bolp) (newline))
              (or (org-previous-line-empty-p)
                  (and blank (newline)))
@@ -5756,13 +6822,16 @@ but create the new headline after the current line."
              (when hide-previous
                (show-children)
                (org-show-entry))
-             (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
+             (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
              (setq tags (and (match-end 2) (match-string 2)))
              (and (match-end 1)
                   (delete-region (match-beginning 1) (match-end 1)))
              (setq pos (point-at-bol))
              (or split (end-of-line 1))
              (delete-horizontal-space)
+             (if (string-match "\\`\\*+\\'"
+                               (buffer-substring (point-at-bol) (point)))
+                 (insert " "))
              (newline (if blank 2 1))
              (when tags
                (save-excursion
@@ -5789,7 +6858,7 @@ but create the new headline after the current line."
     (org-back-to-heading t)
     (if (looking-at
         (if no-tags
-            (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
+            (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@#%]+:[ \t]*\\)?$")
           "\\*+[ \t]+\\([^\r\n]*\\)"))
        (match-string 1) "")))
 
@@ -5804,7 +6873,7 @@ This is a list with the following elements:
 - the tags string, or nil."
   (save-excursion
     (org-back-to-heading t)
-    (if (looking-at org-complex-heading-regexp)
+    (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
        (list (length (match-string 1))
              (org-reduced-level (length (match-string 1)))
              (org-match-string-no-properties 2)
@@ -5874,7 +6943,7 @@ Works for outline headings and for plain lists alike."
   (org-insert-heading arg)
   (cond
    ((org-on-heading-p) (org-do-demote))
-   ((org-at-item-p) (org-indent-item 1))))
+   ((org-at-item-p) (org-indent-item))))
 
 (defun org-insert-todo-subheading (arg)
   "Insert a new subheading with TODO keyword or checkbox and demote it.
@@ -5883,7 +6952,7 @@ Works for outline headings and for plain lists alike."
   (org-insert-todo-heading arg)
   (cond
    ((org-on-heading-p) (org-do-demote))
-   ((org-at-item-p) (org-indent-item 1))))
+   ((org-at-item-p) (org-indent-item))))
 
 ;;; Promotion and Demotion
 
@@ -5947,11 +7016,41 @@ in the region."
            ((eolp) (insert " "))
            ((equal (char-after) ?\ ) (forward-char 1))))))
 
+(defun org-current-level ()
+  "Return the level of the current entry, or nil if before the first headline.
+The level is the number of stars at the beginning of the headline."
+  (save-excursion
+    (let ((outline-regexp (org-get-limited-outline-regexp)))
+      (condition-case nil
+         (progn
+           (org-back-to-heading t)
+           (funcall outline-level))
+       (error nil)))))
+
+(defun org-get-previous-line-level ()
+  "Return the outline depth of the last headline before the current line.
+Returns 0 for the first headline in the buffer, and nil if before the
+first headline."
+  (let ((current-level (org-current-level))
+       (prev-level (when (> (line-number-at-pos) 1)
+                     (save-excursion
+                       (beginning-of-line 0)
+                       (org-current-level)))))
+    (cond ((null current-level) nil) ; Before first headline
+         ((null prev-level) 0)      ; At first headline
+         (prev-level))))
+
 (defun org-reduced-level (l)
   "Compute the effective level of a heading.
 This takes into account the setting of `org-odd-levels-only'."
   (if org-odd-levels-only (1+ (floor (/ l 2))) l))
 
+(defun org-level-increment ()
+  "Return the number of stars that will be added or removed at a
+time to headlines when structure editing, based on the value of
+`org-odd-levels-only'."
+  (if org-odd-levels-only 2 1))
+
 (defun org-get-valid-level (level &optional change)
   "Rectify a level change under the influence of `org-odd-levels-only'
 LEVEL is a current level, CHANGE is by how much the level should be
@@ -5999,6 +7098,42 @@ in the region."
     (if org-adapt-indentation (org-fixup-indentation diff))
     (run-hooks 'org-after-demote-entry-hook)))
 
+(defun org-cycle-level ()
+  "Cycle the level of an empty headline through possible states.
+This goes first to child, then to parent, level, then up the hierarchy.
+After top level, it switches back to sibling level."
+  (interactive)
+  (let ((org-adapt-indentation nil))
+    (when (org-point-at-end-of-empty-headline)
+      (setq this-command 'org-cycle-level) ; Only needed for caching
+      (let ((cur-level (org-current-level))
+            (prev-level (org-get-previous-line-level)))
+        (cond
+         ;; If first headline in file, promote to top-level.
+         ((= prev-level 0)
+          (loop repeat (/ (- cur-level 1) (org-level-increment))
+                do (org-do-promote)))
+         ;; If same level as prev, demote one.
+         ((= prev-level cur-level)
+          (org-do-demote))
+         ;; If parent is top-level, promote to top level if not already.
+         ((= prev-level 1)
+          (loop repeat (/ (- cur-level 1) (org-level-increment))
+                do (org-do-promote)))
+         ;; If top-level, return to prev-level.
+         ((= cur-level 1)
+          (loop repeat (/ (- prev-level 1) (org-level-increment))
+                do (org-do-demote)))
+         ;; If less than prev-level, promote one.
+         ((< cur-level prev-level)
+          (org-do-promote))
+         ;; If deeper than prev-level, promote until higher than
+         ;; prev-level.
+         ((> cur-level prev-level)
+          (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
+                do (org-do-promote))))
+        t))))
+
 (defun org-map-tree (fun)
   "Call FUN for every heading underneath the current one."
   (org-back-to-heading)
@@ -6027,7 +7162,7 @@ in the region."
        (funcall fun)))))
 
 (defun org-fixup-indentation (diff)
-  "Change the indentation in the current entry by DIFF
+  "Change the indentation in the current entry by DIFF.
 However, if any line in the current entry has no indentation, or if it
 would end up with no indentation after the change, nothing at all is done."
   (save-excursion
@@ -6053,7 +7188,9 @@ This will leave level 1 alone, convert level 2 to level 3, level 3 to
 level 5 etc."
   (interactive)
   (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
-    (let ((org-odd-levels-only nil) n)
+    (let ((outline-regexp org-outline-regexp)
+         (outline-level 'org-outline-level)
+         (org-odd-levels-only nil) n)
       (save-excursion
        (goto-char (point-min))
        (while (re-search-forward "^\\*\\*+ " nil t)
@@ -6062,20 +7199,22 @@ level 5 etc."
            (org-demote))
          (end-of-line 1))))))
 
-
 (defun org-convert-to-oddeven-levels ()
-  "Convert an org-mode file with only odd levels to one with odd and even levels.
-This promotes level 3 to level 2, level 5 to level 3 etc.  If the file contains a
-section with an even level, conversion would destroy the structure of the file.  An error
-is signaled in this case."
+  "Convert an org-mode file with only odd levels to one with odd/even levels.
+This promotes level 3 to level 2, level 5 to level 3 etc.  If the
+file contains a section with an even level, conversion would
+destroy the structure of the file.  An error is signaled in this
+case."
   (interactive)
   (goto-char (point-min))
   ;; First check if there are no even levels
   (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
     (org-show-context t)
-    (error "Not all levels are odd in this file.  Conversion not possible."))
+    (error "Not all levels are odd in this file.  Conversion not possible"))
   (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
-    (let ((org-odd-levels-only nil) n)
+    (let ((outline-regexp org-outline-regexp)
+         (outline-level 'org-outline-level)
+         (org-odd-levels-only nil) n)
       (save-excursion
        (goto-char (point-min))
        (while (re-search-forward "^\\*\\*+ " nil t)
@@ -6400,20 +7539,27 @@ If yes, remember the marker and the distance to BEG."
     (save-match-data
       (narrow-to-region
        (progn (org-back-to-heading t) (point))
-       (progn (org-end-of-subtree t) (point))))))
+       (progn (org-end-of-subtree t t)
+             (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
+             (point))))))
 
+(eval-when-compile
+  (defvar org-property-drawer-re))
+
+(defvar org-property-start-re)  ;; defined below
 (defun org-clone-subtree-with-time-shift (n &optional shift)
   "Clone the task (subtree) at point N times.
 The clones will be inserted as siblings.
 
-In interactive use, the user will be prompted for the number of clones
-to be produced, and for a time SHIFT, which may be a repeater as used
-in time stamps, for example `+3d'.
+In interactive use, the user will be prompted for the number of
+clones to be produced, and for a time SHIFT, which may be a
+repeater as used in time stamps, for example `+3d'.
 
-When a valid repeater is given and the entry contains any time stamps,
-the clones will become a sequence in time, with time stamps in the
-subtree shifted for each clone produced.  If SHIFT is nil or the
-empty string, time stamps will be left alone.
+When a valid repeater is given and the entry contains any time
+stamps, the clones will become a sequence in time, with time
+stamps in the subtree shifted for each clone produced.  If SHIFT
+is nil or the empty string, time stamps will be left alone.  The
+ID property of the original subtree is removed.
 
 If the original subtree did contain time stamps with a repeater,
 the following will happen:
@@ -6427,7 +7573,7 @@ the following will happen:
 I this way you can spell out a number of instances of a repeating task,
 and still retain the repeater to cover future instances of the task."
   (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
-  (let (beg end template task
+  (let (beg end template task idprop
            shift-n shift-what doshift nmin nmax (n-no-remove -1))
     (if (not (and (integerp n) (> n 0)))
        (error "Invalid number of replications %s" n))
@@ -6444,7 +7590,9 @@ and still retain the repeater to cover future instances of the task."
     (setq nmin 1 nmax n)
     (org-back-to-heading t)
     (setq beg (point))
+    (setq idprop (org-entry-get nil "ID"))
     (org-end-of-subtree t t)
+    (or (bolp) (insert "\n"))
     (setq end (point))
     (setq template (buffer-substring beg end))
     (when (and doshift
@@ -6454,12 +7602,18 @@ and still retain the repeater to cover future instances of the task."
       (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
     (goto-char end)
     (loop for n from nmin to nmax do
-         (if (not doshift)
-             (setq task template)
-           (with-temp-buffer
-             (insert template)
-             (org-mode)
-             (goto-char (point-min))
+         ;; prepare clone
+         (with-temp-buffer
+           (insert template)
+           (org-mode)
+           (goto-char (point-min))
+           (and idprop (if org-clone-delete-id
+                           (org-entry-delete nil "ID")
+                         (org-id-get-create t)))
+           (while (re-search-forward org-property-start-re nil t)
+             (org-remove-empty-drawer-at "PROPERTIES" (point)))
+           (goto-char (point-min))
+           (when doshift
              (while (re-search-forward org-ts-regexp-both nil t)
                (org-timestamp-change (* n shift-n) shift-what))
              (unless (= n n-no-remove)
@@ -6468,21 +7622,23 @@ and still retain the repeater to cover future instances of the task."
                  (save-excursion
                    (goto-char (match-beginning 0))
                    (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
-                       (delete-region (match-beginning 1) (match-end 1))))))
-             (setq task (buffer-string))))
+                       (delete-region (match-beginning 1) (match-end 1)))))))
+           (setq task (buffer-string)))
          (insert task))
     (goto-char beg)))
 
 ;;; Outline Sorting
 
 (defun org-sort (with-case)
-  "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
+  "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
 Optional argument WITH-CASE means sort case-sensitively.
 With a double prefix argument, also remove duplicate entries."
   (interactive "P")
-  (if (org-at-table-p)
-      (org-call-with-arg 'org-table-sort-lines with-case)
-    (org-call-with-arg 'org-sort-entries-or-items with-case)))
+  (cond
+   ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
+   ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
+   (t
+    (org-call-with-arg 'org-sort-entries with-case))))
 
 (defun org-sort-remove-invisible (s)
   (remove-text-properties 0 (length s) org-rm-props s)
@@ -6500,20 +7656,18 @@ When children are sorted, the cursor is in the parent line when this
 hook gets called.  When a region or a plain list is sorted, the cursor
 will be in the first entry of the sorted region/list.")
 
-(defun org-sort-entries-or-items
+(defun org-sort-entries
   (&optional with-case sorting-type getkey-func compare-func property)
-  "Sort entries on a certain level of an outline tree, or plain list items.
+  "Sort entries on a certain level of an outline tree.
 If there is an active region, the entries in the region are sorted.
 Else, if the cursor is before the first entry, sort the top-level items.
 Else, the children of the entry at point are sorted.
-If the cursor is at the first item in a plain list, the list items will be
-sorted.
 
 Sorting can be alphabetically, numerically, by date/time as given by
 a time stamp, by a property or by priority.
 
 The command prompts for the sorting type unless it has been given to the
-function through the SORTING-TYPE argument, which needs to a character,
+function through the SORTING-TYPE argument, which needs to be a character,
 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F).  Here is the
 precise meaning of each character:
 
@@ -6521,7 +7675,6 @@ n   Numerically, by converting the beginning of the entry/item to a number.
 a   Alphabetically, ignoring the TODO keyword and the priority, if any.
 t   By date/time, either the first active time stamp in the entry, or, if
     none exist, by the first inactive one.
-    In items, only the first line will be chekced.
 s   By the scheduled date/time.
 d   By deadline date/time.
 c   By creation time, which is assumed to be the first inactive time stamp
@@ -6540,7 +7693,7 @@ WITH-CASE, the sorting considers case as well."
   (interactive "P")
   (let ((case-func (if with-case 'identity 'downcase))
         start beg end stars re re2
-        txt what tmp plain-list-p)
+        txt what tmp)
     ;; Find beginning and end of region to sort
     (cond
      ((org-region-active-p)
@@ -6550,19 +7703,13 @@ WITH-CASE, the sorting considers case as well."
       (goto-char (region-beginning))
       (if (not (org-on-heading-p)) (outline-next-heading))
       (setq start (point)))
-     ((org-at-item-p)
-      ;; we will sort this plain list
-      (org-beginning-of-item-list) (setq start (point))
-      (org-end-of-item-list) (setq end (point))
-      (goto-char start)
-      (setq plain-list-p t
-           what "plain list"))
      ((or (org-on-heading-p)
           (condition-case nil (progn (org-back-to-heading) t) (error nil)))
       ;; we will sort the children of the current headline
       (org-back-to-heading)
       (setq start (point)
            end (progn (org-end-of-subtree t t)
+                      (or (bolp) (insert "\n"))
                       (org-back-over-empty-lines)
                       (point))
            what "children")
@@ -6573,50 +7720,54 @@ WITH-CASE, the sorting considers case as well."
       ;; we will sort the top-level entries in this file
       (goto-char (point-min))
       (or (org-on-heading-p) (outline-next-heading))
-      (setq start (point) end (point-max) what "top-level")
+      (setq start (point))
+      (goto-char (point-max))
+      (beginning-of-line 1)
+      (when (looking-at ".*?\\S-")
+       ;; File ends in a non-white line
+       (end-of-line 1)
+       (insert "\n"))
+      (setq end (point-max))
+      (setq what "top-level")
       (goto-char start)
       (show-all)))
 
     (setq beg (point))
     (if (>= beg end) (error "Nothing to sort"))
 
-    (unless plain-list-p
-      (looking-at "\\(\\*+\\)")
-      (setq stars (match-string 1)
-           re (concat "^" (regexp-quote stars) " +")
-           re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
-           txt (buffer-substring beg end))
-      (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
-      (if (and (not (equal stars "*")) (string-match re2 txt))
-         (error "Region to sort contains a level above the first entry")))
+    (looking-at "\\(\\*+\\)")
+    (setq stars (match-string 1)
+         re (concat "^" (regexp-quote stars) " +")
+         re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
+         txt (buffer-substring beg end))
+    (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
+    (if (and (not (equal stars "*")) (string-match re2 txt))
+       (error "Region to sort contains a level above the first entry"))
 
     (unless sorting-type
       (message
-       (if plain-list-p
-          "Sort %s: [a]lpha  [n]umeric  [t]ime  [f]unc   A/N/T/F means reversed:"
-        "Sort %s: [a]lpha  [n]umeric  [p]riority  p[r]operty  todo[o]rder  [f]unc
+       "Sort %s: [a]lpha  [n]umeric  [p]riority  p[r]operty  todo[o]rder  [f]unc
                [t]ime [s]cheduled  [d]eadline  [c]reated
-               A/N/T/S/D/C/P/O/F means reversed:")
+               A/N/T/S/D/C/P/O/F means reversed:"
        what)
       (setq sorting-type (read-char-exclusive))
 
       (and (= (downcase sorting-type) ?f)
            (setq getkey-func
                  (org-icompleting-read "Sort using function: "
-                                  obarray 'fboundp t nil nil))
+                                      obarray 'fboundp t nil nil))
            (setq getkey-func (intern getkey-func)))
 
       (and (= (downcase sorting-type) ?r)
            (setq property
                  (org-icompleting-read "Property: "
-                                 (mapcar 'list (org-buffer-property-keys t))
-                                  nil t))))
+                                      (mapcar 'list (org-buffer-property-keys t))
+                                      nil t))))
 
     (message "Sorting entries...")
 
     (save-restriction
       (narrow-to-region start end)
-
       (let ((dcst (downcase sorting-type))
            (case-fold-search nil)
             (now (current-time)))
@@ -6624,99 +7775,70 @@ WITH-CASE, the sorting considers case as well."
          (/= dcst sorting-type)
          ;; This function moves to the beginning character of the "record" to
          ;; be sorted.
-        (if plain-list-p
-            (lambda nil
-              (if (org-at-item-p) t (goto-char (point-max))))
-          (lambda nil
-            (if (re-search-forward re nil t)
-                (goto-char (match-beginning 0))
-              (goto-char (point-max)))))
+        (lambda nil
+          (if (re-search-forward re nil t)
+              (goto-char (match-beginning 0))
+            (goto-char (point-max))))
          ;; This function moves to the last character of the "record" being
          ;; sorted.
-        (if plain-list-p
-            'org-end-of-item
-          (lambda nil
-            (save-match-data
-              (condition-case nil
-                  (outline-forward-same-level 1)
-                (error
-                 (goto-char (point-max)))))))
-
+        (lambda nil
+          (save-match-data
+            (condition-case nil
+                (outline-forward-same-level 1)
+              (error
+               (goto-char (point-max))))))
          ;; This function returns the value that gets sorted against.
-        (if plain-list-p
-            (lambda nil
-              (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
-                (cond
-                 ((= dcst ?n)
-                  (string-to-number (buffer-substring (match-end 0)
-                                                      (point-at-eol))))
-                 ((= dcst ?a)
-                  (buffer-substring (match-end 0) (point-at-eol)))
-                 ((= dcst ?t)
-                  (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
-                          (re-search-forward org-ts-regexp-both
-                                             (point-at-eol) t))
-                      (org-time-string-to-seconds (match-string 0))
-                    (org-float-time now)))
-                 ((= dcst ?f)
-                  (if getkey-func
-                      (progn
-                        (setq tmp (funcall getkey-func))
-                        (if (stringp tmp) (setq tmp (funcall case-func tmp)))
-                        tmp)
-                    (error "Invalid key function `%s'" getkey-func)))
-                 (t (error "Invalid sorting type `%c'" sorting-type)))))
-          (lambda nil
-            (cond
-             ((= dcst ?n)
-              (if (looking-at org-complex-heading-regexp)
-                  (string-to-number (match-string 4))
-                nil))
-             ((= dcst ?a)
-              (if (looking-at org-complex-heading-regexp)
-                  (funcall case-func (match-string 4))
-                nil))
-             ((= dcst ?t)
-              (let ((end (save-excursion (outline-next-heading) (point))))
-                (if (or (re-search-forward org-ts-regexp end t)
-                        (re-search-forward org-ts-regexp-both end t))
-                    (org-time-string-to-seconds (match-string 0))
-                  (org-float-time now))))
-             ((= dcst ?c)
-              (let ((end (save-excursion (outline-next-heading) (point))))
-                (if (re-search-forward
-                     (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
-                     end t)
-                    (org-time-string-to-seconds (match-string 0))
-                  (org-float-time now))))
-             ((= dcst ?s)
-              (let ((end (save-excursion (outline-next-heading) (point))))
-                (if (re-search-forward org-scheduled-time-regexp end t)
-                    (org-time-string-to-seconds (match-string 1))
-                  (org-float-time now))))
-             ((= dcst ?d)
-              (let ((end (save-excursion (outline-next-heading) (point))))
-                (if (re-search-forward org-deadline-time-regexp end t)
-                    (org-time-string-to-seconds (match-string 1))
-                  (org-float-time now))))
-             ((= dcst ?p)
-              (if (re-search-forward org-priority-regexp (point-at-eol) t)
-                  (string-to-char (match-string 2))
-                org-default-priority))
-             ((= dcst ?r)
-              (or (org-entry-get nil property) ""))
-             ((= dcst ?o)
-              (if (looking-at org-complex-heading-regexp)
-                  (- 9999 (length (member (match-string 2)
-                                          org-todo-keywords-1)))))
-             ((= dcst ?f)
-              (if getkey-func
-                  (progn
-                    (setq tmp (funcall getkey-func))
-                    (if (stringp tmp) (setq tmp (funcall case-func tmp)))
-                    tmp)
-                (error "Invalid key function `%s'" getkey-func)))
-             (t (error "Invalid sorting type `%c'" sorting-type)))))
+        (lambda nil
+          (cond
+           ((= dcst ?n)
+            (if (looking-at org-complex-heading-regexp)
+                (string-to-number (match-string 4))
+              nil))
+           ((= dcst ?a)
+            (if (looking-at org-complex-heading-regexp)
+                (funcall case-func (match-string 4))
+              nil))
+           ((= dcst ?t)
+            (let ((end (save-excursion (outline-next-heading) (point))))
+              (if (or (re-search-forward org-ts-regexp end t)
+                      (re-search-forward org-ts-regexp-both end t))
+                  (org-time-string-to-seconds (match-string 0))
+                (org-float-time now))))
+           ((= dcst ?c)
+            (let ((end (save-excursion (outline-next-heading) (point))))
+              (if (re-search-forward
+                   (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
+                   end t)
+                  (org-time-string-to-seconds (match-string 0))
+                (org-float-time now))))
+           ((= dcst ?s)
+            (let ((end (save-excursion (outline-next-heading) (point))))
+              (if (re-search-forward org-scheduled-time-regexp end t)
+                  (org-time-string-to-seconds (match-string 1))
+                (org-float-time now))))
+           ((= dcst ?d)
+            (let ((end (save-excursion (outline-next-heading) (point))))
+              (if (re-search-forward org-deadline-time-regexp end t)
+                  (org-time-string-to-seconds (match-string 1))
+                (org-float-time now))))
+           ((= dcst ?p)
+            (if (re-search-forward org-priority-regexp (point-at-eol) t)
+                (string-to-char (match-string 2))
+              org-default-priority))
+           ((= dcst ?r)
+            (or (org-entry-get nil property) ""))
+           ((= dcst ?o)
+            (if (looking-at org-complex-heading-regexp)
+                (- 9999 (length (member (match-string 2)
+                                        org-todo-keywords-1)))))
+           ((= dcst ?f)
+            (if getkey-func
+                (progn
+                  (setq tmp (funcall getkey-func))
+                  (if (stringp tmp) (setq tmp (funcall case-func tmp)))
+                  tmp)
+              (error "Invalid key function `%s'" getkey-func)))
+           (t (error "Invalid sorting type `%c'" sorting-type))))
          nil
          (cond
           ((= dcst ?a) 'string<)
@@ -6795,15 +7917,15 @@ If WITH-CASE is non-nil, the sorting will be case-sensitive."
   "Keymap for the minor `orgstruct-mode'.")
 
 (defvar org-local-vars nil
-  "List of local variables, for use by `orgstruct-mode'")
+  "List of local variables, for use by `orgstruct-mode'.")
 
 ;;;###autoload
 (define-minor-mode orgstruct-mode
-  "Toggle the minor more `orgstruct-mode'.
-This mode is for using Org-mode structure commands in other modes.
-The following key behave as if Org-mode was active, if the cursor
-is on a headline, or on a plain list item (both in the definition
-of Org-mode).
+  "Toggle the minor mode `orgstruct-mode'.
+This mode is for using Org-mode structure commands in other
+modes.  The following keys behave as if Org-mode were active, if
+the cursor is on a headline, or on a plain list item (both as
+defined by Org-mode).
 
 M-up        Move entry/item up
 M-down     Move entry/item down
@@ -6854,7 +7976,7 @@ major mode, for example with \\[normal-mode]."
       (org-set-local 'orgstruct-is-++ t))))
 
 (defvar orgstruct-is-++ nil
-  "Is orgstruct-mode in ++ version in the current-buffer?")
+  "Is `orgstruct-mode' in ++ version in the current-buffer?")
 (make-variable-buffer-local 'orgstruct-is-++)
 
 ;;;###autoload
@@ -7096,7 +8218,7 @@ If yes, it should return a non-nil value after a calling
 `org-store-link-props' with a list of properties and values.
 Special properties are:
 
-:type         The link prefix. like \"http\".  This must be given.
+:type         The link prefix, like \"http\".  This must be given.
 :link         The link, like \"http://www.astro.uva.nl/~dominik\".
               This is obligatory as well.
 :description  Optional default description for the second pair
@@ -7121,11 +8243,13 @@ It should be a function accepting three arguments:
 
   path    the path of the link, the text after the prefix (like \"http:\")
   desc    the description of the link, if any, nil if there was no description
-  format  the export format, a symbol like `html' or `latex'.
+  format  the export format, a symbol like `html' or `latex' or `ascii'..
 
 The function may use the FORMAT information to return different values
 depending on the format.  The return value will be put literally into
-the exported file.
+the exported file.  If the return value is nil, this means Org should
+do what it normally does with links which do not have EXPORT defined.
+
 Org-mode has a built-in default for exporting links.  If you are happy with
 this default, there is no need to define an export function for the link
 type.  For a simple example of an export function, see `org-bbdb.el'."
@@ -7135,6 +8259,8 @@ type.  For a simple example of an export function, see `org-bbdb.el'."
       (setcdr (assoc type org-link-protocols) (list follow export))
     (push (list type follow export) org-link-protocols)))
 
+(defvar org-agenda-buffer-name)
+
 ;;;###autoload
 (defun org-store-link (arg)
   "\\<org-mode-map>Store an org-link to the current location.
@@ -7148,7 +8274,7 @@ For file links, arg negates `org-context-in-file-links'."
   (org-load-modules-maybe)
   (setq org-store-link-plist nil)  ; reset
   (let ((outline-regexp (org-get-limited-outline-regexp))
-       link cpltxt desc description search txt custom-id)
+       link cpltxt desc description search txt custom-id agenda-link)
     (cond
 
      ((run-hook-with-args-until-success 'org-store-link-functions)
@@ -7174,6 +8300,17 @@ For file links, arg negates `org-context-in-file-links'."
        (insert link)
        (setq link (concat "(" label ")") desc nil)))
 
+     ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
+      ;; We are in the agenda, link to referenced location
+      (let ((m (or (get-text-property (point) 'org-hd-marker)
+                  (get-text-property (point) 'org-marker))))
+       (when m
+         (org-with-point-at m
+           (setq agenda-link
+                 (if (interactive-p)
+                     (call-interactively 'org-store-link)
+                   (org-store-link nil)))))))
+
      ((eq major-mode 'calendar-mode)
       (let ((cd (calendar-cursor-to-date)))
        (setq link
@@ -7211,19 +8348,23 @@ For file links, arg negates `org-context-in-file-links'."
 
      ((eq major-mode 'dired-mode)
       ;; link to the file in the current line
-      (setq cpltxt (concat "file:"
-                          (abbreviate-file-name
-                           (expand-file-name
-                            (dired-get-filename nil t))))
-           link (org-make-link cpltxt)))
-
-     ((and buffer-file-name (org-mode-p))
+      (let ((file (dired-get-filename nil t)))
+       (setq file (if file
+                      (abbreviate-file-name
+                       (expand-file-name (dired-get-filename nil t)))
+                    ;; otherwise, no file so use current directory.
+                    default-directory))
+       (setq cpltxt (concat "file:" file)
+             link (org-make-link cpltxt))))
+
+     ((and (buffer-file-name (buffer-base-buffer)) (org-mode-p))
       (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
       (cond
        ((org-in-regexp "<<\\(.*?\\)>>")
        (setq cpltxt
              (concat "file:"
-                     (abbreviate-file-name buffer-file-name)
+                     (abbreviate-file-name
+                      (buffer-file-name (buffer-base-buffer)))
                      "::" (match-string 1))
              link (org-make-link cpltxt)))
        ((and (featurep 'org-id)
@@ -7245,11 +8386,13 @@ For file links, arg negates `org-context-in-file-links'."
                     (error
                      ;; probably before first headline, link to file only
                      (concat "file:"
-                             (abbreviate-file-name buffer-file-name))))))
+                             (abbreviate-file-name
+                              (buffer-file-name (buffer-base-buffer))))))))
        (t
        ;; Just link to current headline
        (setq cpltxt (concat "file:"
-                            (abbreviate-file-name buffer-file-name)))
+                            (abbreviate-file-name
+                             (buffer-file-name (buffer-base-buffer)))))
        ;; Add a context search string
        (when (org-xor org-context-in-file-links arg)
          (setq txt (cond
@@ -7263,7 +8406,8 @@ For file links, arg negates `org-context-in-file-links'."
                          (condition-case nil
                              (org-make-org-heading-search-string txt)
                            (error "")))
-                 desc (or (nth 4 (org-heading-components)) "NONE"))))
+                 desc (or (nth 4 (ignore-errors
+                                   (org-heading-components))) "NONE"))))
        (if (string-match "::\\'" cpltxt)
            (setq cpltxt (substring cpltxt 0 -2)))
        (setq link (org-make-link cpltxt)))))
@@ -7305,7 +8449,7 @@ For file links, arg negates `org-context-in-file-links'."
                               "::#" custom-id))
            (setq org-stored-links
                  (cons (list link desc) org-stored-links))))
-      (and link (org-make-link-string link desc)))))
+      (or agenda-link (and link (org-make-link-string link desc))))))
 
 (defun org-store-link-props (&rest plist)
   "Store link properties, extract names and addresses."
@@ -7364,12 +8508,13 @@ according to FMT (default from `org-email-link-description-format')."
 (defun org-make-org-heading-search-string (&optional string heading)
   "Make search string for STRING or current headline."
   (interactive)
-  (let ((s (or string (org-get-heading))))
+  (let ((s (or string (org-get-heading)))
+       (lines org-context-in-file-links))
     (unless (and string (not heading))
       ;; We are using a headline, clean up garbage in there.
       (if (string-match org-todo-regexp s)
          (setq s (replace-match "" t t s)))
-      (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
+      (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
          (setq s (replace-match "" t t s)))
       (setq s (org-trim s))
       (if (string-match (concat "^\\(" org-quote-string "\\|"
@@ -7377,9 +8522,14 @@ according to FMT (default from `org-email-link-description-format')."
          (setq s (replace-match "" t t s)))
       (while (string-match org-ts-regexp s)
        (setq s (replace-match "" t t s))))
-    (while (string-match "[^a-zA-Z_0-9 \t]+" s)
-      (setq s (replace-match " " t t s)))
     (or string (setq s (concat "*" s)))  ; Add * for headlines
+    (when (and string (integerp lines) (> lines 0))
+      (let ((slines (org-split-string s "\n")))
+       (when (< lines (length slines))
+         (setq s (mapconcat 
+                  'identity
+                  (reverse (nthcdr (- (length slines) lines) 
+                                   (reverse slines))) "\n")))))
     (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
 
 (defun org-make-link (&rest strings)
@@ -7390,6 +8540,10 @@ according to FMT (default from `org-email-link-description-format')."
   "Make a link with brackets, consisting of LINK and DESCRIPTION."
   (unless (string-match "\\S-" link)
     (error "Empty link"))
+  (when (and description
+            (stringp description)
+            (not (string-match "\\S-" description)))
+    (setq description nil))
   (when (stringp description)
     ;; Remove brackets from the description, they are fatal.
     (while (string-match "\\[" description)
@@ -7402,7 +8556,11 @@ according to FMT (default from `org-email-link-description-format')."
   (when (and (not description)
             (not (equal link (org-link-escape link))))
     (setq description (org-extract-attributes link)))
-  (concat "[[" (org-link-escape link) "]"
+  (setq link (if (string-match org-link-types-re link)
+                (concat (match-string 1 link)
+                        (org-link-escape (substring link (match-end 1))))
+              (org-link-escape link)))
+  (concat "[[" link "]"
          (if description (concat "[" description "]") "")
          "]"))
 
@@ -7421,7 +8579,7 @@ according to FMT (default from `org-email-link-description-format')."
     (?\371 . "%F9")  ; `u
     (?\373 . "%FB")  ; ^u
     (?\;   . "%3B")
-    (??    . "%3F")
+;;  (??    . "%3F")
     (?=    . "%3D")
     (?+    . "%2B")
     )
@@ -7437,7 +8595,7 @@ This is the list that is used before handing over to the browser.")
 
 (defun org-link-escape (text &optional table)
   "Escape characters in TEXT that are problematic for links."
-  (if org-url-encoding-use-url-hexify
+  (if (and org-url-encoding-use-url-hexify (not table))
       (url-hexify-string text)
     (setq table (or table org-link-escape-chars))
     (when text
@@ -7454,16 +8612,18 @@ This is the list that is used before handing over to the browser.")
 
 (defun org-link-unescape (text &optional table)
   "Reverse the action of `org-link-escape'."
-  (if org-url-encoding-use-url-hexify
+  (if (and org-url-encoding-use-url-hexify (not table))
       (url-unhex-string text)
     (setq table (or table org-link-escape-chars))
     (when text
-      (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
+      (let ((case-fold-search t)
+           (re (mapconcat (lambda (x) (regexp-quote (downcase (cdr x))))
                           table "\\|")))
        (while (string-match re text)
          (setq text
                (replace-match
-                (char-to-string (car (rassoc (match-string 0 text) table)))
+                (char-to-string (car (rassoc (upcase (match-string 0 text))
+                                             table)))
                 t t text)))
        text))))
 
@@ -7473,6 +8633,12 @@ This is the list that is used before handing over to the browser.")
 
 (defun org-fixup-message-id-for-http (s)
   "Replace special characters in a message id, so it can be used in an http query."
+  (when (string-match "%" s)
+    (setq s (mapconcat (lambda (c)
+                        (if (eq c ?%)
+                            "%25"
+                          (char-to-string c)))
+                      s "")))
   (while (string-match "<" s)
     (setq s (replace-match "%3C" t t s)))
   (while (string-match ">" s)
@@ -7565,7 +8731,7 @@ Use TAB to complete link prefixes, then RET for type-specific completion support
                    (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
                  (reverse org-stored-links) "\n"))))
       (let ((cw (selected-window)))
-       (select-window (get-buffer-window "*Org Links*"))
+       (select-window (get-buffer-window "*Org Links*" 'visible))
        (setq truncate-lines t)
        (unless (pos-visible-in-window-p (point-max))
          (org-fit-window-to-buffer))
@@ -7590,6 +8756,8 @@ Use TAB to complete link prefixes, then RET for type-specific completion support
                     nil nil nil
                     'tmphist
                     (car (car org-stored-links)))))
+           (if (not (string-match "\\S-" link))
+               (error "No link selected"))
            (if (or (member link all-prefixes)
                    (and (equal ":" (substring link -1))
                         (member (substring link 0 -1) all-prefixes)
@@ -7622,8 +8790,9 @@ Use TAB to complete link prefixes, then RET for type-specific completion support
              (setq link search)))))
 
     ;; Check if we can/should use a relative path.  If yes, simplify the link
-    (when (string-match "^file:\\(.*\\)" link)
-      (let* ((path (match-string 1 link))
+    (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
+      (let* ((type (match-string 1 link))
+            (path (match-string 2 link))
             (origpath path)
             (case-fold-search nil))
        (cond
@@ -7637,14 +8806,15 @@ Use TAB to complete link prefixes, then RET for type-specific completion support
         (t
          (save-match-data
            (if (string-match (concat "^" (regexp-quote
-                                          (file-name-as-directory
-                                           (expand-file-name "."))))
+                                          (expand-file-name
+                                           (file-name-as-directory
+                                            default-directory))))
                              (expand-file-name path))
                ;; We are linking a file with relative path name.
                (setq path (substring (expand-file-name path)
                                      (match-end 0)))
              (setq path (abbreviate-file-name (expand-file-name path)))))))
-       (setq link (concat "file:" path))
+       (setq link (concat type path))
        (if (equal desc origpath)
            (setq desc path))))
 
@@ -7700,30 +8870,34 @@ Use TAB to complete link prefixes, then RET for type-specific completion support
   "Use iswitch as a completing-read replacement to choose from choices.
 PROMPT is a string to prompt with.  CHOICES is a list of strings to choose
 from."
-  (let ((iswitchb-make-buflist-hook
-         (lambda ()
-           (setq iswitchb-temp-buflist choices))))
+  (let* ((iswitchb-use-virtual-buffers nil)
+        (iswitchb-make-buflist-hook
+         (lambda ()
+           (setq iswitchb-temp-buflist choices))))
     (iswitchb-read-buffer prompt)))
 
 (defun org-icompleting-read (&rest args)
-  "Completing-read using `ido-mode' or `iswitchb' speedups if available"
-  (if (and org-completion-use-ido
-          (fboundp 'ido-completing-read)
-          (boundp 'ido-mode) ido-mode
-          (listp (second args)))
-      (let ((ido-enter-matching-directory nil))
-       (apply 'ido-completing-read (concat (car args))
-              (if (consp (car (nth 1 args)))
-                  (mapcar (lambda (x) (car x)) (nth 1 args))
-                (nth 1 args))
-              (cddr args)))
-    (if (and org-completion-use-iswitchb
-            (boundp 'iswitchb-mode) iswitchb-mode
-            (listp (second args)))
-       (apply 'org-iswitchb-completing-read (concat (car args))
-              (mapcar (lambda (x) (car x)) (nth 1 args))
-              (cddr args))
-      (apply 'completing-read args))))
+  "Completing-read using `ido-mode' or `iswitchb' speedups if available."
+  (org-without-partial-completion
+   (if (and org-completion-use-ido
+           (fboundp 'ido-completing-read)
+           (boundp 'ido-mode) ido-mode
+           (listp (second args)))
+       (let ((ido-enter-matching-directory nil))
+        (apply 'ido-completing-read (concat (car args))
+               (if (consp (car (nth 1 args)))
+                   (mapcar (lambda (x) (car x)) (nth 1 args))
+                 (nth 1 args))
+               (cddr args)))
+     (if (and org-completion-use-iswitchb
+             (boundp 'iswitchb-mode) iswitchb-mode
+             (listp (second args)))
+        (apply 'org-iswitchb-completing-read (concat (car args))
+               (if (consp (car (nth 1 args)))
+                   (mapcar (lambda (x) (car x)) (nth 1 args))
+                 (nth 1 args))
+               (cddr args))
+       (apply 'completing-read args)))))
 
 (defun org-extract-attributes (s)
   "Extract the attributes cookie from a string and set as text property."
@@ -7759,6 +8933,23 @@ from."
 
 (defvar org-link-search-failed nil)
 
+(defvar org-open-link-functions nil
+  "Hook for functions finding a plain text link.
+These functions must take a single argument, the link content.
+They will be called for links that look like [[link text][description]]
+when LINK TEXT does not have a protocol like \"http:\" and does not look
+like a filename (e.g. \"./blue.png\").
+
+These functions will be called *before* Org attempts to resolve the
+link by doing text searches in the current buffer - so if you want a
+link \"[[target]]\" to still find \"<<target>>\", your function should
+handle this as a special case.
+
+When the function does handle the link, it must return a non-nil value.
+If it decides that it is not responsible for this link, it must return
+nil to indicate that that Org-mode can continue with other options
+like exact and fuzzy text search.")
+
 (defun org-next-link ()
   "Move forward to the next link.
 If the link is in hidden text, expose it."
@@ -7825,7 +9016,7 @@ This is still an experimental function, your mileage may vary."
    ;; Planner has a slash, we do not.
    (setq type "elisp" path (substring path 1)))
   ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
-   ;; A typical message link.  Planner has the id after the fina slash,
+   ;; A typical message link.  Planner has the id after the final slash,
    ;; we separate it with a hash mark
    (setq path (concat (match-string 1 path) "#"
                      (org-remove-angle-brackets (match-string 2 path)))))
@@ -7871,8 +9062,19 @@ Org-mode syntax."
        (org-mode)
        (insert s)
        (goto-char (point-min))
+       (when reference-buffer
+         (setq org-link-abbrev-alist-local
+               (with-current-buffer reference-buffer
+                 org-link-abbrev-alist-local)))
        (org-open-at-point arg reference-buffer)))))
 
+(defvar org-open-at-point-functions nil
+  "Hook that is run when following a link at point.
+
+Functions in this hook must return t if they identify and follow
+a link at point.  If they don't find anything interesting at point,
+they must return nil.")
+
 (defun org-open-at-point (&optional in-emacs reference-buffer)
   "Open link at or after point.
 If there is no link at point, this function will search forward up to
@@ -7882,6 +9084,8 @@ optional argument IN-EMACS is non-nil, Emacs will visit the file.
 With a double prefix argument, try to open outside of Emacs, in the
 application the system uses for this file type."
   (interactive "P")
+  ;; if in a code block, then open the block's results
+  (unless (call-interactively #'org-babel-open-src-block-result)
   (org-load-modules-maybe)
   (move-marker org-open-link-marker (point))
   (setq org-window-config-before-follow-link (current-window-configuration))
@@ -7889,20 +9093,24 @@ application the system uses for this file type."
   (cond
    ((and (org-on-heading-p)
         (not (org-in-regexp
-              (concat org-plain-link-re "\\|" 
+              (concat org-plain-link-re "\\|"
                       org-bracket-link-regexp "\\|"
                       org-angle-link-re "\\|"
-                      "[ \t]:[^ \t\n]+:[ \t]*$"))))
-    (org-offer-links-in-entry in-emacs))
+                      "[ \t]:[^ \t\n]+:[ \t]*$")))
+        (not (get-text-property (point) 'org-linked-text)))
+    (or (org-offer-links-in-entry in-emacs)
+       (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
+   ((run-hook-with-args-until-success 'org-open-at-point-functions))
    ((org-at-timestamp-p t) (org-follow-timestamp-link))
-   ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
+   ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
+        (not (org-in-regexp org-bracket-link-regexp)))
     (org-footnote-action))
    (t
     (let (type path link line search (pos (point)))
       (catch 'match
        (save-excursion
          (skip-chars-forward "^]\n\r")
-         (when (org-in-regexp org-bracket-link-regexp)
+         (when (org-in-regexp org-bracket-link-regexp 1)
            (setq link (org-extract-attributes
                        (org-link-unescape (org-match-string-no-properties 1))))
            (while (string-match " *\n *" link)
@@ -7932,7 +9140,7 @@ application the system uses for this file type."
            (setq type (match-string 1) path (match-string 2))
            (throw 'match t)))
        (save-excursion
-         (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
+         (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
            (setq type "tags"
                  path (match-string 1))
            (while (string-match ":" path)
@@ -7958,12 +9166,12 @@ application the system uses for this file type."
            ;; Check if we need to translate the link
            (let ((tmp (funcall org-link-translation-function type path)))
              (setq type (car tmp) path (cdr tmp))))
-       
+
        (cond
-        
+
         ((assoc type org-link-protocols)
          (funcall (nth 1 (assoc type org-link-protocols)) path))
-        
+
         ((equal type "mailto")
          (let ((cmd (car org-link-mailto-program))
                (args (cdr org-link-mailto-program)) args1
@@ -7981,33 +9189,25 @@ application the system uses for this file type."
                      (setq a (replace-match subject t t a)))
                  (push a args1))))
            (apply cmd (nreverse args1))))
-        
+
         ((member type '("http" "https" "ftp" "news"))
          (browse-url (concat type ":" (org-link-escape
                                        path org-link-escape-chars-browser))))
-        
+
+        ((string= type "doi")
+         (browse-url (concat "http://dx.doi.org/"
+                              (org-link-escape
+                               path org-link-escape-chars-browser))))
+
         ((member type '("message"))
          (browse-url (concat type ":" path)))
-        
+
         ((string= type "tags")
          (org-tags-view in-emacs path))
-        ((string= type "thisfile")
-         (if in-emacs
-             (switch-to-buffer-other-window
-              (org-get-buffer-for-internal-link (current-buffer)))
-           (org-mark-ring-push))
-         (let ((cmd `(org-link-search
-                      ,path
-                      ,(cond ((equal in-emacs '(4)) 'occur)
-                             ((equal in-emacs '(16)) 'org-occur)
-                             (t nil))
-                      ,pos)))
-           (condition-case nil (eval cmd)
-             (error (progn (widen) (eval cmd))))))
-        
+
         ((string= type "tree-match")
          (org-occur (concat "\\[" (regexp-quote path) "\\]")))
-        
+
         ((string= type "file")
          (if (string-match "::\\([0-9]+\\)\\'" path)
              (setq line (string-to-number (match-string 1 path))
@@ -8018,11 +9218,7 @@ application the system uses for this file type."
          (if (string-match "[*?{]" (file-name-nondirectory path))
              (dired path)
            (org-open-file path in-emacs line search)))
-        
-        ((string= type "news")
-         (require 'org-gnus)
-         (org-gnus-follow-link path))
-        
+
         ((string= type "shell")
          (let ((cmd path))
            (if (or (not org-confirm-shell-link-function)
@@ -8034,7 +9230,7 @@ application the system uses for this file type."
                  (message "Executing %s" cmd)
                  (shell-command cmd))
              (error "Abort"))))
-        
+
         ((string= type "elisp")
          (let ((cmd path))
            (if (or (not org-confirm-elisp-link-function)
@@ -8047,23 +9243,45 @@ application the system uses for this file type."
                             (eval (read cmd))
                           (call-interactively (read cmd))))
              (error "Abort"))))
-        
+
+        ((and (string= type "thisfile")
+              (run-hook-with-args-until-success
+               'org-open-link-functions path)))
+
+        ((string= type "thisfile")
+         (if in-emacs
+             (switch-to-buffer-other-window
+              (org-get-buffer-for-internal-link (current-buffer)))
+           (org-mark-ring-push))
+         (let ((cmd `(org-link-search
+                      ,path
+                      ,(cond ((equal in-emacs '(4)) 'occur)
+                             ((equal in-emacs '(16)) 'org-occur)
+                             (t nil))
+                      ,pos)))
+           (condition-case nil (eval cmd)
+             (error (progn (widen) (eval cmd))))))
+
         (t
-         (browse-url-at-point))))))
-   (move-marker org-open-link-marker nil)
-   (run-hook-with-args 'org-follow-link-hook)))
+         (browse-url-at-point)))))))
+  (move-marker org-open-link-marker nil)
+  (run-hook-with-args 'org-follow-link-hook)))
 
-(defun org-offer-links-in-entry (&optional nth)
-  "Offer links in the curren entry and follow the selected link.
+(defun org-offer-links-in-entry (&optional nth zero)
+  "Offer links in the current entry and follow the selected link.
 If there is only one link, follow it immediately as well.
-If NTH is an integer immediately pick the NTH link found."
+If NTH is an integer, immediately pick the NTH link found.
+If ZERO is a string, check also this string for a link, and if
+there is one, offer it as link number zero."
   (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
                    "\\(" org-angle-link-re "\\)\\|"
                    "\\(" org-plain-link-re "\\)"))
        (cnt ?0)
        (in-emacs (if (integerp nth) nil nth))
-       end
-       links link c)
+       have-zero end links link c)
+    (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
+      (push (match-string 0 zero) links)
+      (setq cnt (1- cnt) have-zero t))
     (save-excursion
       (org-back-to-heading t)
       (setq end (save-excursion (outline-next-heading) (point)))
@@ -8072,17 +9290,17 @@ If NTH is an integer immediately pick the NTH link found."
       (setq links (org-uniquify (reverse links))))
 
     (cond
-     ((null links) (error "No links"))
+     ((null links)
+      (message "No links"))
      ((equal (length links) 1)
-      (setq link (car links)))
-     ((and (integerp nth) (>= (length links) nth))
-      (setq link (nth (1- nth) links)))
+      (setq link (list (car links))))
+     ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
+      (setq link (nth (if have-zero nth (1- nth)) links)))
      (t ; we have to select a link
       (save-excursion
        (save-window-excursion
          (delete-other-windows)
          (with-output-to-temp-buffer "*Select Link*"
-           (princ "Select link\n\n")
            (mapc (lambda (l)
                    (if (not (string-match org-bracket-link-regexp l))
                        (princ (format "[%c]  %s\n" (incf cnt)
@@ -8094,15 +9312,43 @@ If NTH is an integer immediately pick the NTH link found."
                                       (match-string 1 l))))))
                  links))
          (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
-         (message "Select link to open:")
+         (message "Select link to open, RET to open all:")
          (setq c (read-char-exclusive))
          (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
       (when (equal c ?q) (error "Abort"))
-      (setq nth (- c ?0))
-      (unless (and (integerp nth) (>= (length links) nth))
-       (error "Invalid link selection"))
-      (setq link (nth (1- nth) links))))
-    (org-open-link-from-string link in-emacs (current-buffer))))
+      (if (equal c ?\C-m)
+         (setq link links)
+       (setq nth (- c ?0))
+       (if have-zero (setq nth (1+ nth)))
+       (unless (and (integerp nth) (>= (length links) nth))
+         (error "Invalid link selection"))
+       (setq link (list (nth (1- nth) links))))))
+    (if link
+       (let ((buf (current-buffer)))
+         (dolist (l link)
+           (org-open-link-from-string l in-emacs buf))
+         t)
+      nil)))
+
+;; Add special file links that specify the way of opening
+
+(org-add-link-type "file+sys" 'org-open-file-with-system)
+(org-add-link-type "file+emacs" 'org-open-file-with-emacs)
+(defun org-open-file-with-system (path)
+  "Open file at PATH using the system way of opening it."
+  (org-open-file path 'system))
+(defun org-open-file-with-emacs (path)
+  "Open file at PATH in Emacs."
+  (org-open-file path 'emacs))
+(defun org-remove-file-link-modifiers ()
+  "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
+  (goto-char (point-min))
+  (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
+    (org-if-unprotected
+     (replace-match "file:" t t))))
+(eval-after-load "org-exp"
+  '(add-hook 'org-export-preprocess-before-normalizing-links-hook
+            'org-remove-file-link-modifiers))
 
 ;;;; Time estimates
 
@@ -8118,8 +9364,8 @@ These functions are called in turn with point at the location to
 which the link should point.
 
 A function in the hook should first test if it would like to
-handle this file type, for example by checking the major-mode or
-the file extension.  If it decides not to handle this file, it
+handle this file type, for example by checking the `major-mode'
+or the file extension.  If it decides not to handle this file, it
 should just return nil to give other functions a chance.  If it
 does handle the file, it must return the search string to be used
 when following the link.  The search string will be part of the
@@ -8140,8 +9386,8 @@ buffer with \\[org-insert-link].")
 Functions added to this hook must accept a single argument, the
 search string that was part of the file link, the part after the
 double colon.  The function must first check if it would like to
-handle this search, for example by checking the major-mode or the
-file extension.  If it decides not to handle this search, it
+handle this search, for example by checking the `major-mode' or
+the file extension.  If it decides not to handle this search, it
 should just return nil to give other functions a chance.  If it
 does handle the search, it must return a non-nil value to keep
 other functions from trying.
@@ -8156,6 +9402,7 @@ the window configuration before `org-open-at-point' was called using:
 
     (set-window-configuration org-window-config-before-follow-link)")
 
+(defvar org-link-search-inhibit-query nil) ;; dynamically scoped
 (defun org-link-search (s &optional type avoid-pos)
   "Search for a link search option.
 If S is surrounded by forward slashes, it is interpreted as a
@@ -8173,7 +9420,7 @@ in all files.  If AVOID-POS is given, ignore matches near that position."
        (pre nil) (post nil)
        words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
     (cond
-     ;; First check if there are any special
+     ;; First check if there are any special search functions
      ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
      ;; Now try the builtin stuff
      ((and (equal (string-to-char s0) ?#)
@@ -8218,12 +9465,33 @@ in all files.  If AVOID-POS is given, ignore matches near that position."
        ;;((eq major-mode 'dired-mode)
        ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
        (t (org-do-occur (match-string 1 s)))))
+     ((and (org-mode-p) org-link-search-must-match-exact-headline)
+      (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
+      (goto-char (point-min))
+      (cond
+       ((let (case-fold-search)
+         (re-search-forward (format org-complex-heading-regexp-format
+                                    (regexp-quote s))
+                            nil t))
+       ;; OK, found a match
+       (setq type 'dedicated)
+       (goto-char (match-beginning 0)))
+       ((and (not org-link-search-inhibit-query)
+            (eq org-link-search-must-match-exact-headline 'query-to-create)
+            (y-or-n-p "No match - create this as a new heading? "))
+       (goto-char (point-max))
+       (or (bolp) (newline))
+       (insert "* " s "\n")
+       (beginning-of-line 0))
+       (t
+       (goto-char pos)
+       (error "No match"))))
      (t
-      ;; A normal search strings
+      ;; A normal search string
       (when (equal (string-to-char s) ?*)
        ;; Anchor on headlines, post may include tags.
        (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
-             post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
+             post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
              s (substring s 1)))
       (remove-text-properties
        0 (length s)
@@ -8264,13 +9532,7 @@ in all files.  If AVOID-POS is given, ignore matches near that position."
                  )
              (goto-char (match-beginning 1))
            (goto-char pos)
-           (error "No match")))))
-     (t
-      ;; Normal string-search
-      (goto-char (point-min))
-      (if (search-forward s nil t)
-         (goto-char (match-beginning 0))
-       (error "No match"))))
+           (error "No match"))))))
     (and (org-mode-p) (org-show-context 'link-search))
     type))
 
@@ -8413,18 +9675,23 @@ entry for this file type, and if yes, the corresponding command is launched.
 If no application is found, Emacs simply visits the file.
 
 With optional prefix argument IN-EMACS, Emacs will visit the file.
-With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
-and o use an external application to visit the file.
-
-Optional LINE specifies a line to go to, optional SEARCH a string to
-search for.  If LINE or SEARCH is given, the file will always be
-opened in Emacs.
+With a double \\[universal-argument] \\[universal-argument] \
+prefix arg, Org tries to avoid opening in Emacs
+and to use an external application to visit the file.
+
+Optional LINE specifies a line to go to, optional SEARCH a string
+to search for.  If LINE or SEARCH is given, the file will be
+opened in Emacs, unless an entry from org-file-apps that makes
+use of groups in a regexp matches.
 If the file does not exist, an error is thrown."
-  (setq in-emacs (or in-emacs line search))
   (let* ((file (if (equal path "")
                   buffer-file-name
                 (substitute-in-file-name (expand-file-name path))))
-        (apps (append org-file-apps (org-default-apps)))
+        (file-apps (append org-file-apps (org-default-apps)))
+        (apps (org-remove-if
+               'org-file-apps-entry-match-against-dlink-p file-apps))
+        (apps-dlink (org-remove-if-not
+                     'org-file-apps-entry-match-against-dlink-p file-apps))
         (remp (and (assq 'remote apps) (org-file-remote-p file)))
         (dirp (if remp nil (file-directory-p file)))
         (file (if (and dirp org-open-directory-means-index-dot-org)
@@ -8432,21 +9699,41 @@ If the file does not exist, an error is thrown."
                 file))
         (a-m-a-p (assq 'auto-mode apps))
         (dfile (downcase file))
+        ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
+        (link (cond ((and (eq line nil)
+                           (eq search nil))
+                      file)
+                     (line
+                     (concat file "::" (number-to-string line)))
+                    (search
+                     (concat file "::" search))))
+        (dlink (downcase link))
         (old-buffer (current-buffer))
         (old-pos (point))
         (old-mode major-mode)
-        ext cmd)
+        ext cmd link-match-data)
     (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
        (setq ext (match-string 1 dfile))
       (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
          (setq ext (match-string 1 dfile))))
     (cond
-     ((equal in-emacs '(16))
+     ((member in-emacs '((16) system))
       (setq cmd (cdr (assoc 'system apps))))
      (in-emacs (setq cmd 'emacs))
      (t
       (setq cmd (or (and remp (cdr (assoc 'remote apps)))
                    (and dirp (cdr (assoc 'directory apps)))
+                   ; first, try matching against apps-dlink
+                   ; if we get a match here, store the match data for later
+                   (let ((match (assoc-default dlink apps-dlink
+                                               'string-match)))
+                     (if match
+                         (progn (setq link-match-data (match-data))
+                                match)
+                       (progn (setq in-emacs (or in-emacs line search))
+                              nil))) ; if we have no match in apps-dlink,
+                                     ; always open the file in emacs if line or search
+                                     ; is given (for backwards compatibility)
                    (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
                                   'string-match)
                    (cdr (assoc ext apps))
@@ -8478,6 +9765,19 @@ If the file does not exist, an error is thrown."
                     (shell-quote-argument
                      (convert-standard-filename file)))
                   t t cmd)))
+
+      ;; Replace "%1", "%2" etc. in command with group matches from regex
+      (save-match-data
+       (let ((match-index 1)
+             (number-of-groups (- (/ (length link-match-data) 2) 1)))
+         (set-match-data link-match-data)
+         (while (<= match-index number-of-groups)
+           (let ((regex (concat "%" (number-to-string match-index)))
+                 (replace-with (match-string match-index dlink)))
+             (while (string-match regex cmd)
+               (setq cmd (replace-match replace-with t t cmd))))
+           (setq match-index (+ match-index 1)))))
+
       (save-window-excursion
        (start-process-shell-command cmd nil cmd)
        (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
@@ -8490,13 +9790,34 @@ If the file does not exist, an error is thrown."
        (if search (org-link-search search))))
      ((consp cmd)
       (let ((file (convert-standard-filename file)))
-       (eval cmd)))
+       (save-match-data
+         (set-match-data link-match-data)
+         (eval cmd))))
      (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
     (and (org-mode-p) (eq old-mode 'org-mode)
         (or (not (equal old-buffer (current-buffer)))
             (not (equal old-pos (point))))
         (org-mark-ring-push old-pos old-buffer))))
 
+(defun org-file-apps-entry-match-against-dlink-p (entry)
+  "This function returns non-nil if `entry' uses a regular
+expression which should be matched against the whole link by
+org-open-file.
+
+It assumes that is the case when the entry uses a regular
+expression which has at least one grouping construct and the
+action is either a lisp form or a command string containing
+'%1', i.e. using at least one subexpression match as a
+parameter."
+  (let ((selector (car entry))
+       (action (cdr entry)))
+    (if (stringp selector)
+       (and (> (regexp-opt-depth selector) 0)
+            (or (and (stringp action)
+                     (string-match "%[0-9]" action))
+                (consp action)))
+      nil)))
+
 (defun org-default-apps ()
   "Return the default applications for this operating system."
   (cond
@@ -8571,12 +9892,64 @@ on the system \"/user@host:\"."
 (defvar org-agenda-new-buffers nil
   "Buffers created to visit agenda files.")
 
+(defvar org-refile-cache nil
+  "Cache for refile targets.")
+
+
+(defvar org-refile-markers nil
+  "All the markers used for caching refile locations.")
+
+(defun org-refile-marker (pos)
+  "Get a new refile marker, but only if caching is in use."
+  (if (not org-refile-use-cache)
+      pos
+    (let ((m (make-marker)))
+      (move-marker m pos)
+      (push m org-refile-markers)
+      m)))
+
+(defun org-refile-cache-clear ()
+  "Clear the refile cache and disable all the markers."
+  (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
+  (setq org-refile-markers nil)
+  (setq org-refile-cache nil)
+  (message "Refile cache has been cleared"))
+
+(defun org-refile-cache-check-set (set)
+  "Check if all the markers in the cache still have live buffers."
+  (let (marker)
+    (catch 'exit
+      (while (and set (setq marker (nth 3 (pop set))))
+       ;; if org-refile-use-outline-path is 'file, marker may be nil
+       (when (and marker (null (marker-buffer marker)))
+         (message "not found") (sit-for 3)
+         (throw 'exit nil)))
+      t)))
+
+(defun org-refile-cache-put (set &rest identifiers)
+  "Push the refile targets SET into the cache, under IDENTIFIERS."
+  (let* ((key (sha1 (prin1-to-string identifiers)))
+        (entry (assoc key org-refile-cache)))
+    (if entry
+       (setcdr entry set)
+      (push (cons key set) org-refile-cache))))
+
+(defun org-refile-cache-get (&rest identifiers)
+  "Retrieve the cached value for refile targets given by IDENTIFIERS."
+  (cond
+   ((not org-refile-cache) nil)
+   ((not org-refile-use-cache) (org-refile-cache-clear) nil)
+   (t
+    (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
+                          org-refile-cache))))
+      (and set (org-refile-cache-check-set set) set)))))
+
 (defun org-get-refile-targets (&optional default-buffer)
   "Produce a table with refile targets."
   (let ((case-fold-search nil)
        ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
        (entries (or org-refile-targets '((nil . (:level . 1)))))
-       targets txt re files f desc descre fast-path-p level pos0)
+       targets tgs txt re files f desc descre fast-path-p level pos0)
     (message "Getting targets...")
     (with-current-buffer (or default-buffer (current-buffer))
       (while (setq entry (pop entries))
@@ -8613,48 +9986,60 @@ on the system \"/user@host:\"."
                               "\\}[ \t]")))
         (t (error "Bad refiling target description %s" desc)))
        (while (setq f (pop files))
-         (save-excursion
-           (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
-           (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
-           (setq f (expand-file-name f))
-           (if (eq org-refile-use-outline-path 'file)
-               (push (list (file-name-nondirectory f) f nil nil) targets))
-           (save-excursion
-             (save-restriction
-               (widen)
-               (goto-char (point-min))
-               (while (re-search-forward descre nil t)
-                 (goto-char (setq pos0 (point-at-bol)))
-                 (catch 'next
-                   (when org-refile-target-verify-function
-                     (save-match-data
-                       (or (funcall org-refile-target-verify-function)
-                           (throw 'next t))))
-                   (when (looking-at org-complex-heading-regexp)
-                     (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
-                           txt (org-link-display-format (match-string 4))
-                           re (concat "^" (regexp-quote
-                                           (buffer-substring (match-beginning 1)
-                                                             (match-end 4)))))
-                     (if (match-end 5) (setq re (concat re "[ \t]+"
-                                                        (regexp-quote
-                                                         (match-string 5)))))
-                     (setq re (concat re "[ \t]*$"))
-                     (when org-refile-use-outline-path
-                       (setq txt (mapconcat 'org-protect-slash
-                                            (append
-                                             (if (eq org-refile-use-outline-path 'file)
-                                                 (list (file-name-nondirectory
-                                                        (buffer-file-name (buffer-base-buffer))))
-                                               (if (eq org-refile-use-outline-path 'full-file-path)
-                                                   (list (buffer-file-name (buffer-base-buffer)))))
-                                             (org-get-outline-path fast-path-p level txt)
-                                             (list txt))
-                                            "/")))
-                     (push (list txt f re (point)) targets)))
-                 (when (= (point) pos0)
-                   ;; verification function has not moved point
-                   (goto-char (point-at-eol))))))))))
+         (with-current-buffer
+             (if (bufferp f) f (org-get-agenda-file-buffer f))
+           (or
+            (setq tgs (org-refile-cache-get (buffer-file-name) descre))
+            (progn
+              (if (bufferp f) (setq f (buffer-file-name
+                                       (buffer-base-buffer f))))
+              (setq f (and f (expand-file-name f)))
+              (if (eq org-refile-use-outline-path 'file)
+                  (push (list (file-name-nondirectory f) f nil nil) tgs))
+              (save-excursion
+                (save-restriction
+                  (widen)
+                  (goto-char (point-min))
+                  (while (re-search-forward descre nil t)
+                    (goto-char (setq pos0 (point-at-bol)))
+                    (catch 'next
+                      (when org-refile-target-verify-function
+                        (save-match-data
+                          (or (funcall org-refile-target-verify-function)
+                              (throw 'next t))))
+                      (when (looking-at org-complex-heading-regexp)
+                        (setq level (org-reduced-level
+                                     (- (match-end 1) (match-beginning 1)))
+                              txt (org-link-display-format (match-string 4))
+                              txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
+                              re (format org-complex-heading-regexp-format
+                                         (regexp-quote (match-string 4))))
+                        (when org-refile-use-outline-path
+                          (setq txt (mapconcat
+                                     'org-protect-slash
+                                     (append
+                                      (if (eq org-refile-use-outline-path
+                                              'file)
+                                          (list (file-name-nondirectory
+                                                 (buffer-file-name
+                                                  (buffer-base-buffer))))
+                                        (if (eq org-refile-use-outline-path
+                                                'full-file-path)
+                                            (list (buffer-file-name
+                                                   (buffer-base-buffer)))))
+                                      (org-get-outline-path fast-path-p
+                                                            level txt)
+                                      (list txt))
+                                     "/")))
+                        (push (list txt f re (org-refile-marker (point)))
+                              tgs)))
+                    (when (= (point) pos0)
+                      ;; verification function has not moved point
+                      (goto-char (point-at-eol))))))))
+           (when org-refile-use-cache
+             (org-refile-cache-put tgs (buffer-file-name) descre))
+           (setq targets (append tgs targets))
+           ))))
     (message "Getting targets...done")
     (nreverse targets)))
 
@@ -8666,22 +10051,83 @@ on the system \"/user@host:\"."
 (defvar org-olpa (make-vector 20 nil))
 
 (defun org-get-outline-path (&optional fastp level heading)
-  "Return the outline path to the current entry, as a list."
+  "Return the outline path to the current entry, as a list.
+
+The parameters FASTP, LEVEL, and HEADING are for use by a scanner
+routine which makes outline path derivations for an entire file,
+avoiding backtracing.  Refile target collection makes use of that."
   (if fastp
       (progn
        (if (> level 19)
-           (error "Outline path failure, more than 19 levels."))
+           (error "Outline path failure, more than 19 levels"))
        (loop for i from level upto 19 do
              (aset org-olpa i nil))
        (prog1
            (delq nil (append org-olpa nil))
          (aset org-olpa level heading)))
-    (let (rtn)
+    (let (rtn case-fold-search)
       (save-excursion
-       (while (org-up-heading-safe)
-         (when (looking-at org-complex-heading-regexp)
-           (push (org-match-string-no-properties 4) rtn)))
-       rtn))))
+       (save-restriction
+         (widen)
+         (while (org-up-heading-safe)
+           (when (looking-at org-complex-heading-regexp)
+             (push (org-match-string-no-properties 4) rtn)))
+         rtn)))))
+
+(defun org-format-outline-path (path &optional width prefix)
+  "Format the outline path PATH for display.
+Width is the maximum number of characters that is available.
+Prefix is a prefix to be included in the returned string,
+such as the file name."
+  (setq width (or width 79))
+  (if prefix (setq width (- width (length prefix))))
+  (if (not path)
+      (or prefix "")
+    (let* ((nsteps (length path))
+          (total-width (+ nsteps (apply '+ (mapcar 'length path))))
+          (maxwidth (if (<= total-width width)
+                        10000  ;; everything fits
+                      ;; we need to shorten the level headings
+                      (/ (- width nsteps) nsteps)))
+          (org-odd-levels-only nil)
+          (n 0)
+          (total (1+ (length prefix))))
+      (setq maxwidth (max maxwidth 10))
+      (concat prefix
+             (mapconcat
+              (lambda (h)
+                (setq n (1+ n))
+                (if (and (= n nsteps) (< maxwidth 10000))
+                    (setq maxwidth (- total-width total)))
+                (if (< (length h) maxwidth)
+                    (progn (setq total (+ total (length h) 1)) h)
+                  (setq h (substring h 0 (- maxwidth 2))
+                        total (+ total maxwidth 1))
+                  (if (string-match "[ \t]+\\'" h)
+                      (setq h (substring h 0 (match-beginning 0))))
+                  (setq h (concat  h "..")))
+                (org-add-props h nil 'face
+                               (nth (% (1- n) org-n-level-faces)
+                                    org-level-faces))
+                h)
+              path "/")))))
+
+(defun org-display-outline-path (&optional file current)
+  "Display the current outline path in the echo area."
+  (interactive "P")
+  (let* ((bfn (buffer-file-name (buffer-base-buffer)))
+        (case-fold-search nil)
+        (path (and (org-mode-p) (org-get-outline-path))))
+    (if current (setq path (append path
+                                  (save-excursion
+                                    (org-back-to-heading t)
+                                    (if (looking-at org-complex-heading-regexp)
+                                        (list (match-string 4)))))))
+    (message "%s"
+            (org-format-outline-path
+             path
+             (1- (frame-width))
+             (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
 
 (defvar org-refile-history nil
   "History for refiling operations.")
@@ -8691,6 +10137,7 @@ on the system \"/user@host:\"."
 Note that this is still *before* the stuff will be removed from
 the *old* location.")
 
+(defvar org-capture-last-stored-marker)
 (defun org-refile (&optional goto default-buffer rfloc)
   "Move the entry at point to another heading.
 The list of target headings is compiled using the information in
@@ -8702,102 +10149,130 @@ Depending on `org-reverse-note-order', the new subitem will either be the
 first or the last subitem.
 
 If there is an active region, all entries in that region will be moved.
-However, the region must fulfil the requirement that the first heading
+However, the region must fulfill the requirement that the first heading
 is the first one sets the top-level of the moved text - at most siblings
 below it are allowed.
 
 With prefix arg GOTO, the command will only visit the target location,
 not actually move anything.
-With a double prefix `C-u C-u', go to the location where the last refiling
+With a double prefix arg \\[universal-argument] \\[universal-argument], \
+go to the location where the last refiling
 operation has put the subtree.
+With a prefix argument of `2', refile to the running clock.
 
 RFLOC can be a refile location obtained in a different way.
 
-See also `org-refile-use-outline-path' and `org-completion-use-ido'"
+See also `org-refile-use-outline-path' and `org-completion-use-ido'.
+
+If you are using target caching (see `org-refile-use-cache'),
+You have to clear the target cache in order to find new targets.
+This can be done with a 0 prefix: `C-0 C-c C-w'"
   (interactive "P")
-  (let* ((cbuf (current-buffer))
-        (regionp (org-region-active-p))
-        (region-start (and regionp (region-beginning)))
-        (region-end (and regionp (region-end)))
-        (region-length (and regionp (- region-end region-start)))
-        (filename (buffer-file-name (buffer-base-buffer cbuf)))
-        pos it nbuf file re level reversed)
-    (when regionp
-      (goto-char region-start)
-      (or (bolp) (goto-char (point-at-bol)))
-      (setq region-start (point))
-      (unless (org-kill-is-subtree-p
-              (buffer-substring region-start region-end))
-       (error "The region is not a (sequence of) subtree(s)")))
-    (if (equal goto '(16))
-       (org-refile-goto-last-stored)
-      (when (setq it (or rfloc
-                        (save-excursion
-                          (org-refile-get-location
-                           (if goto "Goto: " "Refile to: ") default-buffer
-                           org-refile-allow-creating-parent-nodes))))
-       (setq file (nth 1 it)
-             re (nth 2 it)
-             pos (nth 3 it))
-       (if (and (not goto)
-                pos
-                (equal (buffer-file-name) file)
-                (if regionp
-                    (and (>= pos region-start)
-                         (<= pos region-end))
-                  (and (>= pos (point))
-                       (< pos (save-excursion
-                                (org-end-of-subtree t t))))))
-           (error "Cannot refile to position inside the tree or region"))
-
-       (setq nbuf (or (find-buffer-visiting file)
-                      (find-file-noselect file)))
-       (if goto
-           (progn
-             (switch-to-buffer nbuf)
-             (goto-char pos)
-             (org-show-context 'org-goto))
-         (if regionp
+  (if (member goto '(0 (64)))
+      (org-refile-cache-clear)
+    (let* ((cbuf (current-buffer))
+          (regionp (org-region-active-p))
+          (region-start (and regionp (region-beginning)))
+          (region-end (and regionp (region-end)))
+          (region-length (and regionp (- region-end region-start)))
+          (filename (buffer-file-name (buffer-base-buffer cbuf)))
+          pos it nbuf file re level reversed)
+      (setq last-command nil)
+      (when regionp
+       (goto-char region-start)
+       (or (bolp) (goto-char (point-at-bol)))
+       (setq region-start (point))
+       (unless (org-kill-is-subtree-p
+                (buffer-substring region-start region-end))
+         (error "The region is not a (sequence of) subtree(s)")))
+      (if (equal goto '(16))
+         (org-refile-goto-last-stored)
+       (when (or
+              (and (equal goto 2)
+                   org-clock-hd-marker (marker-buffer org-clock-hd-marker)
+                   (prog1
+                       (setq it (list (or org-clock-heading "running clock")
+                                      (buffer-file-name
+                                       (marker-buffer org-clock-hd-marker))
+                                      ""
+                                      (marker-position org-clock-hd-marker)))
+                     (setq goto nil)))
+              (setq it (or rfloc
+                           (save-excursion
+                             (org-refile-get-location
+                              (if goto "Goto: " "Refile to: ") default-buffer
+                              org-refile-allow-creating-parent-nodes)))))
+         (setq file (nth 1 it)
+               re (nth 2 it)
+               pos (nth 3 it))
+         (if (and (not goto)
+                  pos
+                  (equal (buffer-file-name) file)
+                  (if regionp
+                      (and (>= pos region-start)
+                           (<= pos region-end))
+                    (and (>= pos (point))
+                         (< pos (save-excursion
+                                  (org-end-of-subtree t t))))))
+             (error "Cannot refile to position inside the tree or region"))
+
+         (setq nbuf (or (find-buffer-visiting file)
+                        (find-file-noselect file)))
+         (if goto
              (progn
-               (org-kill-new (buffer-substring region-start region-end))
-               (org-save-markers-in-region region-start region-end))
-           (org-copy-subtree 1 nil t))
-         (save-excursion
-           (set-buffer (setq nbuf (or (find-buffer-visiting file)
-                                      (find-file-noselect file))))
-           (setq reversed (org-notes-order-reversed-p))
-           (save-excursion
-             (save-restriction
-               (widen)
-               (if pos
-                   (progn
-                     (goto-char pos)
-                     (looking-at outline-regexp)
-                     (setq level (org-get-valid-level (funcall outline-level) 1))
-                     (goto-char
-                      (if reversed
-                          (or (outline-next-heading) (point-max))
-                        (or (save-excursion (org-get-next-sibling))
-                            (org-end-of-subtree t t)
-                            (point-max)))))
-                 (setq level 1)
-                 (if (not reversed)
-                     (goto-char (point-max))
-                   (goto-char (point-min))
-                   (or (outline-next-heading) (goto-char (point-max)))))
-               (if (not (bolp)) (newline))
-               (bookmark-set "org-refile-last-stored")
-               (org-paste-subtree level)
-               (if (fboundp 'deactivate-mark) (deactivate-mark))
-               (run-hooks 'org-after-refile-insert-hook))))
-         (if regionp
-             (delete-region (point) (+ (point) region-length))
-           (org-cut-subtree))
-         (when (featurep 'org-inlinetask)
-           (org-inlinetask-remove-END-maybe))
-         (setq org-markers-to-move nil)
-         (message "Refiled to \"%s\"" (car it))))))
-  (org-reveal))
+               (switch-to-buffer nbuf)
+               (goto-char pos)
+               (org-show-context 'org-goto))
+           (if regionp
+               (progn
+                 (org-kill-new (buffer-substring region-start region-end))
+                 (org-save-markers-in-region region-start region-end))
+             (org-copy-subtree 1 nil t))
+           (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
+                                               (find-file-noselect file)))
+             (setq reversed (org-notes-order-reversed-p))
+             (save-excursion
+               (save-restriction
+                 (widen)
+                 (if pos
+                     (progn
+                       (goto-char pos)
+                       (looking-at outline-regexp)
+                       (setq level (org-get-valid-level (funcall outline-level) 1))
+                       (goto-char
+                        (if reversed
+                            (or (outline-next-heading) (point-max))
+                          (or (save-excursion (org-get-next-sibling))
+                              (org-end-of-subtree t t)
+                              (point-max)))))
+                   (setq level 1)
+                   (if (not reversed)
+                       (goto-char (point-max))
+                     (goto-char (point-min))
+                     (or (outline-next-heading) (goto-char (point-max)))))
+                 (if (not (bolp)) (newline))
+                 (org-paste-subtree level)
+                 (when org-log-refile
+                   (org-add-log-setup 'refile nil nil 'findpos
+                                      org-log-refile)
+                   (unless (eq org-log-refile 'note)
+                     (save-excursion (org-add-log-note))))
+                 (and org-auto-align-tags (org-set-tags nil t))
+                 (bookmark-set "org-refile-last-stored")
+                 ;; If we are refiling for capture, make sure that the
+                 ;; last-capture pointers point here
+                 (when (org-bound-and-true-p org-refile-for-capture)
+                   (bookmark-set "org-capture-last-stored-marker")
+                   (move-marker org-capture-last-stored-marker (point)))
+                 (if (fboundp 'deactivate-mark) (deactivate-mark))
+                 (run-hooks 'org-after-refile-insert-hook))))
+           (if regionp
+               (delete-region (point) (+ (point) region-length))
+             (org-cut-subtree))
+           (when (featurep 'org-inlinetask)
+             (org-inlinetask-remove-END-maybe))
+           (setq org-markers-to-move nil)
+           (message "Refiled to \"%s\" in file %s" (car it) file)))))))
 
 (defun org-refile-goto-last-stored ()
   "Go to the location where the last refile was stored."
@@ -8837,7 +10312,8 @@ See also `org-refile-use-outline-path' and `org-completion-use-ido'"
     (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
                        nil 'org-refile-history))
     (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
-    (if pa 
+    (org-refile-check-position pa)
+    (if pa
        (progn
          (when (or (not org-refile-history)
                    (not (eq old-hist org-refile-history))
@@ -8849,15 +10325,39 @@ See also `org-refile-use-outline-path' and `org-completion-use-ido'"
            (if (equal (car org-refile-history) (nth 1 org-refile-history))
                (pop org-refile-history)))
          pa)
-      (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
-       (setq parent (match-string 1 answ)
-             child (match-string 2 answ))
-       (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
-       (when (and parent-target
-                  (or (eq new-nodes t)
-                      (and (eq new-nodes 'confirm)
-                           (y-or-n-p (format "Create new node \"%s\"? " child)))))
-         (org-refile-new-child parent-target child))))))
+      (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
+         (progn
+           (setq parent (match-string 1 answ)
+                 child (match-string 2 answ))
+           (setq parent-target (or (assoc parent tbl)
+                                   (assoc (concat parent "/") tbl)))
+           (when (and parent-target
+                      (or (eq new-nodes t)
+                          (and (eq new-nodes 'confirm)
+                               (y-or-n-p (format "Create new node \"%s\"? "
+                                                 child)))))
+             (org-refile-new-child parent-target child)))
+       (error "Invalid target location")))))
+
+(defun org-refile-check-position (refile-pointer)
+  "Check if the refile pointer matches the readline to which it points."
+  (let* ((file (nth 1 refile-pointer))
+        (re (nth 2 refile-pointer))
+        (pos (nth 3 refile-pointer))
+        buffer)
+    (when (org-string-nw-p re)
+      (setq buffer (if (markerp pos)
+                      (marker-buffer pos)
+                    (or (find-buffer-visiting file)
+                        (find-file-noselect file))))
+      (with-current-buffer buffer
+       (save-excursion
+         (save-restriction
+           (widen)
+           (goto-char pos)
+           (beginning-of-line 1)
+           (unless (org-looking-at-p re)
+             (error "Invalid refile position, please rebuild the cache"))))))))
 
 (defun org-refile-new-child (parent-target child)
   "Use refile target PARENT-TARGET to add new CHILD below it."
@@ -8889,7 +10389,7 @@ See also `org-refile-use-outline-path' and `org-completion-use-ido'"
   "Read an outline path like a file name."
   (let ((thetable collection)
        (org-completion-use-ido nil)       ; does not work with ido.
-       (org-completion-use-iswitchb nil)) ; or iswitchb 
+       (org-completion-use-iswitchb nil)) ; or iswitchb
     (apply
      'org-icompleting-read prompt
      (lambda (string predicate &optional flag)
@@ -8932,23 +10432,26 @@ If not found, stay at current position and return nil."
     pos))
 
 (defconst org-dblock-start-re
-  "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
-  "Matches the startline of a dynamic block, with parameters.")
+  "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
+  "Matches the start line of a dynamic block, with parameters.")
 
-(defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
+(defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
   "Matches the end of a dynamic block.")
 
 (defun org-create-dblock (plist)
   "Create a dynamic block section, with parameters taken from PLIST.
 PLIST must contain a :name entry which is used as name of the block."
-  (unless (bolp) (newline))
-  (let ((name (plist-get plist :name)))
+  (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
+    (end-of-line 1)
+    (newline))
+  (let ((col (current-column))
+       (name (plist-get plist :name)))
     (insert "#+BEGIN: " name)
     (while plist
       (if (eq (car plist) :name)
          (setq plist (cddr plist))
        (insert " " (prin1-to-string (pop plist)))))
-    (insert "\n\n#+END:\n")
+    (insert "\n\n" (make-string col ?\ ) "#+END:\n")
     (beginning-of-line -2)))
 
 (defun org-prepare-dblock ()
@@ -8961,6 +10464,10 @@ the property list including an extra property :name with the block name."
         (name (org-no-properties (match-string 1)))
         (params (append (list :name name)
                         (read (concat "(" (match-string 3) ")")))))
+    (save-excursion
+      (beginning-of-line 1)
+      (skip-chars-forward " \t")
+      (setq params (plist-put params :indentation-column (current-column))))
     (unless (re-search-forward org-dblock-end-re nil t)
       (error "Dynamic block not terminated"))
     (setq params
@@ -8975,16 +10482,15 @@ the property list including an extra property :name with the block name."
 (defun org-map-dblocks (&optional command)
   "Apply COMMAND to all dynamic blocks in the current buffer.
 If COMMAND is not given, use `org-update-dblock'."
-  (let ((cmd (or command 'org-update-dblock))
-       pos)
+  (let ((cmd (or command 'org-update-dblock)))
     (save-excursion
       (goto-char (point-min))
       (while (re-search-forward org-dblock-start-re nil t)
-       (goto-char (setq pos (match-beginning 0)))
-       (condition-case nil
-           (funcall cmd)
-         (error (message "Error during update of dynamic block")))
-       (goto-char pos)
+       (goto-char (match-beginning 0))
+        (save-excursion
+          (condition-case nil
+              (funcall cmd)
+            (error (message "Error during update of dynamic block"))))
        (unless (re-search-forward org-dblock-end-re nil t)
          (error "Dynamic block not terminated"))))))
 
@@ -9000,19 +10506,33 @@ blocks in the buffer."
     (org-update-dblock)))
 
 (defun org-update-dblock ()
-  "Update the dynamic block at point
+  "Update the dynamic block at point.
 This means to empty the block, parse for parameters and then call
 the correct writing function."
+  (interactive)
   (save-window-excursion
     (let* ((pos (point))
           (line (org-current-line))
           (params (org-prepare-dblock))
           (name (plist-get params :name))
+          (indent (plist-get params :indentation-column))
           (cmd (intern (concat "org-dblock-write:" name))))
       (message "Updating dynamic block `%s' at line %d..." name line)
       (funcall cmd params)
       (message "Updating dynamic block `%s' at line %d...done" name line)
-      (goto-char pos))))
+      (goto-char pos)
+      (when (and indent (> indent 0))
+       (setq indent (make-string indent ?\ ))
+       (save-excursion
+       (org-beginning-of-dblock)
+       (forward-line 1)
+       (while (not (looking-at org-dblock-end-re))
+         (insert indent)
+         (beginning-of-line 2))
+       (when (looking-at org-dblock-end-re)
+         (and (looking-at "[ \t]+")
+              (replace-match ""))
+         (insert indent)))))))
 
 (defun org-beginning-of-dblock ()
   "Find the beginning of the dynamic block at point.
@@ -9031,6 +10551,7 @@ Error if there is no such block at point."
 (defun org-update-all-dblocks ()
   "Update all dynamic blocks in the buffer.
 This function can be used in a hook."
+  (interactive)
   (when (org-mode-p)
     (org-map-dblocks 'org-update-dblock)))
 
@@ -9038,9 +10559,10 @@ This function can be used in a hook."
 ;;;; Completion
 
 (defconst org-additional-option-like-keywords
-  '("BEGIN_HTML"  "END_HTML"  "HTML:" "ATTR_HTML"
-    "BEGIN_DocBook"  "END_DocBook"  "DocBook:" "ATTR_DocBook"
-    "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"  "ATTR_LaTeX"
+  '("BEGIN_HTML"  "END_HTML"  "HTML:" "ATTR_HTML:"
+    "BEGIN_DocBook"  "END_DocBook"  "DocBook:" "ATTR_DocBook:"
+    "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
+    "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
     "BEGIN:" "END:"
     "ORGTBL" "TBLFM:" "TBLNAME:"
     "BEGIN_EXAMPLE" "END_EXAMPLE"
@@ -9048,10 +10570,17 @@ This function can be used in a hook."
     "BEGIN_VERSE" "END_VERSE"
     "BEGIN_CENTER" "END_CENTER"
     "BEGIN_SRC" "END_SRC"
-    "CATEGORY" "COLUMNS"
-    "CAPTION" "LABEL"
-    "BIND"
-    "MACRO"))
+    "BEGIN_RESULT" "END_RESULT"
+    "SOURCE:" "SRCNAME:" "FUNCTION:"
+    "RESULTS:"
+    "HEADER:" "HEADERS:"
+    "BABEL:"
+    "CATEGORY:" "COLUMNS:" "PROPERTY:"
+    "CAPTION:" "LABEL:"
+    "SETUPFILE:"
+    "INCLUDE:"
+    "BIND:"
+    "MACRO:"))
 
 (defcustom org-structure-template-alist
   '(
@@ -9080,12 +10609,12 @@ This function can be used in a hook."
     )
   "Structure completion elements.
 This is a list of abbreviation keys and values.  The value gets inserted
-it you type @samp{.} followed by the key and then the completion key,
+if you type `<' followed by the key and then press the completion key,
 usually `M-TAB'.  %file will be replaced by a file name after prompting
 for the file using completion.
 There are two templates for each key, the first uses the original Org syntax,
 the second uses Emacs Muse-like syntax tags.  These Muse-like tags become
-the default when the /org-mtags.el/ module has been loaded. See also the
+the default when the /org-mtags.el/ module has been loaded.  See also the
 variable `org-mtags-prefer-muse-templates'.
 This is an experimental feature, it is undecided if it is going to stay in."
   :group 'org-completion
@@ -9133,132 +10662,6 @@ expands them."
     (insert rpl)
     (if (re-search-backward "\\?" start t) (delete-char 1))))
 
-
-(defun org-complete (&optional arg)
-  "Perform completion on word at point.
-At the beginning of a headline, this completes TODO keywords as given in
-`org-todo-keywords'.
-If the current word is preceded by a backslash, completes the TeX symbols
-that are supported for HTML support.
-If the current word is preceded by \"#+\", completes special words for
-setting file options.
-In the line after \"#+STARTUP:, complete valid keywords.\"
-At all other locations, this simply calls the value of
-`org-completion-fallback-command'."
-  (interactive "P")
-  (org-without-partial-completion
-   (catch 'exit
-     (let* ((a nil)
-           (end (point))
-           (beg1 (save-excursion
-                   (skip-chars-backward (org-re "[:alnum:]_@"))
-                   (point)))
-           (beg (save-excursion
-                  (skip-chars-backward "a-zA-Z0-9_:$")
-                  (point)))
-           (confirm (lambda (x) (stringp (car x))))
-           (searchhead (equal (char-before beg) ?*))
-           (struct
-            (when (and (member (char-before beg1) '(?. ?<))
-                       (setq a (assoc (buffer-substring beg1 (point))
-                                      org-structure-template-alist)))
-              (org-complete-expand-structure-template (1- beg1) a)
-              (throw 'exit t)))
-           (tag (and (equal (char-before beg1) ?:)
-                     (equal (char-after (point-at-bol)) ?*)))
-           (prop (and (equal (char-before beg1) ?:)
-                      (not (equal (char-after (point-at-bol)) ?*))))
-           (texp (equal (char-before beg) ?\\))
-           (link (equal (char-before beg) ?\[))
-           (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
-                                         beg)
-                       "#+"))
-           (startup (string-match "^#\\+STARTUP:.*"
-                                  (buffer-substring (point-at-bol) (point))))
-           (completion-ignore-case opt)
-           (type nil)
-           (tbl nil)
-           (table (cond
-                   (opt
-                    (setq type :opt)
-                    (require 'org-exp)
-                    (append
-                     (delq nil
-                           (mapcar
-                            (lambda (x)
-                              (if (string-match
-                                   "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
-                                  (cons (match-string 2 x)
-                                        (match-string 1 x))))
-                            (org-split-string (org-get-current-options) "\n")))
-                     (mapcar 'list org-additional-option-like-keywords)))
-                   (startup
-                    (setq type :startup)
-                    org-startup-options)
-                   (link (append org-link-abbrev-alist-local
-                                 org-link-abbrev-alist))
-                   (texp
-                    (setq type :tex)
-                    org-html-entities)
-                   ((string-match "\\`\\*+[ \t]+\\'"
-                                  (buffer-substring (point-at-bol) beg))
-                    (setq type :todo)
-                    (mapcar 'list org-todo-keywords-1))
-                   (searchhead
-                    (setq type :searchhead)
-                    (save-excursion
-                      (goto-char (point-min))
-                      (while (re-search-forward org-todo-line-regexp nil t)
-                        (push (list
-                               (org-make-org-heading-search-string
-                                (match-string 3) t))
-                              tbl)))
-                    tbl)
-                   (tag (setq type :tag beg beg1)
-                        (or org-tag-alist (org-get-buffer-tags)))
-                   (prop (setq type :prop beg beg1)
-                         (mapcar 'list (org-buffer-property-keys nil t t)))
-                   (t (progn
-                        (call-interactively org-completion-fallback-command)
-                        (throw 'exit nil)))))
-           (pattern (buffer-substring-no-properties beg end))
-           (completion (try-completion pattern table confirm)))
-       (cond ((eq completion t)
-             (if (not (assoc (upcase pattern) table))
-                 (message "Already complete")
-               (if (and (equal type :opt)
-                        (not (member (car (assoc (upcase pattern) table))
-                                     org-additional-option-like-keywords)))
-                   (insert (substring (cdr (assoc (upcase pattern) table))
-                                      (length pattern)))
-                 (if (memq type '(:tag :prop)) (insert ":")))))
-            ((null completion)
-             (message "Can't find completion for \"%s\"" pattern)
-             (ding))
-            ((not (string= pattern completion))
-             (delete-region beg end)
-             (if (string-match " +$" completion)
-                 (setq completion (replace-match "" t t completion)))
-             (insert completion)
-             (if (get-buffer-window "*Completions*")
-                 (delete-window (get-buffer-window "*Completions*")))
-             (if (assoc completion table)
-                 (if (eq type :todo) (insert " ")
-                   (if (memq type '(:tag :prop)) (insert ":"))))
-             (if (and (equal type :opt) (assoc completion table))
-                 (message "%s" (substitute-command-keys
-                                "Press \\[org-complete] again to insert example settings"))))
-            (t
-             (message "Making completion list...")
-             (let ((list (sort (all-completions pattern table confirm)
-                               'string<)))
-               (with-output-to-temp-buffer "*Completions*"
-                 (condition-case nil
-                     ;; Protection needed for XEmacs and emacs 21
-                     (display-completion-list list pattern)
-                   (error (display-completion-list list)))))
-             (message "Making completion list...%s" "done")))))))
-
 ;;;; TODO, DEADLINE, Comments
 
 (defun org-toggle-comment ()
@@ -9282,38 +10685,15 @@ this is nil.")
 
 (defvar org-setting-tags nil) ; dynamically skipped
 
-(defun org-parse-local-options (string var)
-  "Parse STRING for startup setting relevant for variable VAR."
-  (let ((rtn (symbol-value var))
-       e opts)
-    (save-match-data
-      (if (or (not string) (not (string-match "\\S-" string)))
-         rtn
-       (setq opts (delq nil (mapcar (lambda (x)
-                                      (setq e (assoc x org-startup-options))
-                                      (if (eq (nth 1 e) var) e nil))
-                                    (org-split-string string "[ \t]+"))))
-       (if (not opts)
-           rtn
-         (setq rtn nil)
-         (while (setq e (pop opts))
-           (if (not (nth 3 e))
-               (setq rtn (nth 2 e))
-             (if (not (listp rtn)) (setq rtn nil))
-             (push (nth 2 e) rtn)))
-         rtn)))))
-
 (defvar org-todo-setup-filter-hook nil
   "Hook for functions that pre-filter todo specs.
-
-Each function takes a todo spec and returns either `nil' or the spec
+Each function takes a todo spec and returns either nil or the spec
 transformed into canonical form." )
 
 (defvar org-todo-get-default-hook nil
   "Hook for functions that get a default item for todo.
-
 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
-`nil' or a string to be used for the todo mark." )
+nil or a string to be used for the todo mark." )
 
 (defvar org-agenda-headline-snapshot-before-repeat)
 
@@ -9330,10 +10710,12 @@ So for this example: when the item starts with TODO, it is changed to DONE.
 When it starts with DONE, the DONE is removed.  And when neither TODO nor
 DONE are present, add TODO at the beginning of the heading.
 
-With C-u prefix arg, use completion to determine the new state.
+With \\[universal-argument] prefix arg, use completion to determine the new \
+state.
 With numeric prefix arg, switch to that state.
-With a double C-u prefix, switch to the next set of TODO keywords (nextset).
-With a tripple C-u prefix, circumvent any state blocking.
+With a double \\[universal-argument] prefix, switch to the next set of TODO \
+keywords (nextset).
+With a triple \\[universal-argument] prefix, circumvent any state blocking.
 
 For calling through lisp, arg is also interpreted in the following way:
 'none             -> empty state
@@ -9355,13 +10737,13 @@ For calling through lisp, arg is also interpreted in the following way:
       (setq org-blocker-hook nil))
     (save-excursion
       (catch 'exit
-       (org-back-to-heading)
+       (org-back-to-heading t)
        (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
        (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
            (looking-at " *"))
        (let* ((match-data (match-data))
               (startpos (point-at-bol))
-              (logging (save-match-data (org-entry-get nil "LOGGING" t)))
+              (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
               (org-log-done org-log-done)
               (org-log-repeat org-log-repeat)
               (org-todo-log-states org-todo-log-states)
@@ -9421,6 +10803,8 @@ For calling through lisp, arg is also interpreted in the following way:
                            (or (car (cdr (member head org-todo-heads)))
                                (car org-todo-heads))))
                         ((car (member arg org-todo-keywords-1)))
+                        ((stringp arg)
+                         (error "State `%s' not valid in this file" arg))
                         ((nth (1- (prefix-numeric-value arg))
                               org-todo-keywords-1))))
                       ((null member) (or head (car org-todo-keywords-1)))
@@ -9541,53 +10925,56 @@ changes.  Such blocking occurs when:
   3. The parent of the task is blocked because it has siblings that should
      be done first, or is child of a block grandparent TODO entry."
 
-  (catch 'dont-block
-    ;; If this is not a todo state change, or if this entry is already DONE,
-    ;; do not block
-    (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
-             (member (plist-get change-plist :from)
-                     (cons 'done org-done-keywords))
-             (member (plist-get change-plist :to)
-                     (cons 'todo org-not-done-keywords)))
-      (throw 'dont-block t))
-    ;; If this task has children, and any are undone, it's blocked
-    (save-excursion
-      (org-back-to-heading t)
-      (let ((this-level (funcall outline-level)))
-       (outline-next-heading)
-       (let ((child-level (funcall outline-level)))
-         (while (and (not (eobp))
-                     (> child-level this-level))
-           ;; this todo has children, check whether they are all
-           ;; completed
-           (if (and (not (org-entry-is-done-p))
-                    (org-entry-is-todo-p))
-               (throw 'dont-block nil))
-           (outline-next-heading)
-           (setq child-level (funcall outline-level))))))
-    ;; Otherwise, if the task's parent has the :ORDERED: property, and
-    ;; any previous siblings are undone, it's blocked
-    (save-excursion
-      (org-back-to-heading t)
-      (let* ((pos (point))
-            (parent-pos (and (org-up-heading-safe) (point))))
-       (if (not parent-pos) (throw 'dont-block t)) ; no parent
-       (when (and (org-entry-get (point) "ORDERED")
-                  (forward-line 1)
-                  (re-search-forward org-not-done-heading-regexp pos t))
-         (throw 'dont-block nil)) ; block, there is an older sibling not done.
-       ;; Search further up the hierarchy, to see if an anchestor is blocked
-       (while t
-         (goto-char parent-pos)
-         (if (not (looking-at org-not-done-heading-regexp))
-             (throw 'dont-block t)) ; do not block, parent is not a TODO
-         (setq pos (point))
-         (setq parent-pos (and (org-up-heading-safe) (point)))
+  (if (not org-enforce-todo-dependencies)
+      t ; if locally turned off don't block
+    (catch 'dont-block
+      ;; If this is not a todo state change, or if this entry is already DONE,
+      ;; do not block
+      (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
+               (member (plist-get change-plist :from)
+                       (cons 'done org-done-keywords))
+               (member (plist-get change-plist :to)
+                       (cons 'todo org-not-done-keywords))
+               (not (plist-get change-plist :to)))
+       (throw 'dont-block t))
+      ;; If this task has children, and any are undone, it's blocked
+      (save-excursion
+       (org-back-to-heading t)
+       (let ((this-level (funcall outline-level)))
+         (outline-next-heading)
+         (let ((child-level (funcall outline-level)))
+           (while (and (not (eobp))
+                       (> child-level this-level))
+             ;; this todo has children, check whether they are all
+             ;; completed
+             (if (and (not (org-entry-is-done-p))
+                      (org-entry-is-todo-p))
+                 (throw 'dont-block nil))
+             (outline-next-heading)
+             (setq child-level (funcall outline-level))))))
+      ;; Otherwise, if the task's parent has the :ORDERED: property, and
+      ;; any previous siblings are undone, it's blocked
+      (save-excursion
+       (org-back-to-heading t)
+       (let* ((pos (point))
+              (parent-pos (and (org-up-heading-safe) (point))))
          (if (not parent-pos) (throw 'dont-block t)) ; no parent
-         (when (and (org-entry-get (point) "ORDERED")
+         (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
                     (forward-line 1)
                     (re-search-forward org-not-done-heading-regexp pos t))
-           (throw 'dont-block nil))))))) ; block, older sibling not done.
+           (throw 'dont-block nil))  ; block, there is an older sibling not done.
+         ;; Search further up the hierarchy, to see if an anchestor is blocked
+         (while t
+           (goto-char parent-pos)
+           (if (not (looking-at org-not-done-heading-regexp))
+               (throw 'dont-block t))  ; do not block, parent is not a TODO
+           (setq pos (point))
+           (setq parent-pos (and (org-up-heading-safe) (point)))
+           (if (not parent-pos) (throw 'dont-block t)) ; no parent
+           (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
+                      (forward-line 1)
+                      (re-search-forward org-not-done-heading-regexp pos t))
+             (throw 'dont-block nil)))))))) ; block, older sibling not done.
 
 (defcustom org-track-ordered-property-with-tag nil
   "Should the ORDERED property also be shown as a tag?
@@ -9630,30 +11017,45 @@ See variable `org-track-ordered-property-with-tag'."
 (defun org-block-todo-from-checkboxes (change-plist)
   "Block turning an entry into a TODO, using checkboxes.
 This checks whether the current task should be blocked from state
-changes because there are uncheckd boxes in this entry."
-  (catch 'dont-block
-    ;; If this is not a todo state change, or if this entry is already DONE,
-    ;; do not block
-    (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
-             (member (plist-get change-plist :from)
-                     (cons 'done org-done-keywords))
-             (member (plist-get change-plist :to)
-                     (cons 'todo org-not-done-keywords)))
-      (throw 'dont-block t))
-    ;; If this task has checkboxes that are not checked, it's blocked
-    (save-excursion
-      (org-back-to-heading t)
-      (let ((beg (point)) end)
-       (outline-next-heading)
-       (setq end (point))
-       (goto-char beg)
-       (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
-                              end t)
-           (progn
-             (if (boundp 'org-blocked-by-checkboxes)
-                 (setq org-blocked-by-checkboxes t))
-             (throw 'dont-block nil)))))
-    t)) ; do not block
+changes because there are unchecked boxes in this entry."
+  (if (not org-enforce-todo-checkbox-dependencies)
+      t ; if locally turned off don't block
+    (catch 'dont-block
+      ;; If this is not a todo state change, or if this entry is already DONE,
+      ;; do not block
+      (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
+               (member (plist-get change-plist :from)
+                       (cons 'done org-done-keywords))
+               (member (plist-get change-plist :to)
+                       (cons 'todo org-not-done-keywords))
+               (not (plist-get change-plist :to)))
+       (throw 'dont-block t))
+      ;; If this task has checkboxes that are not checked, it's blocked
+      (save-excursion
+       (org-back-to-heading t)
+       (let ((beg (point)) end)
+         (outline-next-heading)
+         (setq end (point))
+         (goto-char beg)
+         (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
+                                end t)
+             (progn
+               (if (boundp 'org-blocked-by-checkboxes)
+                   (setq org-blocked-by-checkboxes t))
+               (throw 'dont-block nil)))))
+      t))) ; do not block
+
+(defun org-entry-blocked-p ()
+  "Is the current entry blocked?"
+  (if (org-entry-get nil "NOBLOCKING")
+      nil ;; Never block this entry
+    (not
+     (run-hook-with-args-until-failure
+      'org-blocker-hook
+      (list :type 'todo-state-change
+           :position (point)
+           :from 'todo
+           :to 'done)))))
 
 (defun org-update-statistics-cookies (all)
   "Update the statistics cookie, either from TODO or from checkboxes.
@@ -9675,8 +11077,9 @@ This should be called with the cursor in a line with a statistics cookie."
                      (outline-next-heading)
                      (if (org-on-heading-p) (setq l2 (org-outline-level)))
                      (point)))
-         (if (and (save-excursion (re-search-forward
-                                   "^[ \t]*[-+*] \\[[- X]\\]" end t))
+         (if (and (save-excursion
+                    (re-search-forward
+                     "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
                   (not (save-excursion (re-search-forward
                                         ":COOKIE_DATA:.*\\<todo\\>" end t))))
              (org-update-checkbox-count)
@@ -9684,10 +11087,15 @@ This should be called with the cursor in a line with a statistics cookie."
                (progn
                  (goto-char end)
                  (org-update-parent-todo-statistics))
-             (error "No data for statistics cookie"))))
+             (goto-char pos)
+             (beginning-of-line 1)
+             (while (re-search-forward
+                     "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
+                     (point-at-eol) t)
+               (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
        (goto-char pos)
        (move-marker pos nil)))))
-  
+
 (defvar org-entry-property-inherited-from) ;; defined below
 (defun org-update-parent-todo-statistics ()
   "Update any statistics cookie in the parent of the current headline.
@@ -9706,7 +11114,7 @@ statistics everywhere."
                  lim))
         (first t)
         (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
-        level ltoggle l1
+        level ltoggle l1 new ndel
         (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
     (catch 'exit
       (save-excursion
@@ -9717,7 +11125,7 @@ statistics everywhere."
        (while (and (setq level (org-up-heading-safe))
                    (or recursive first)
                    (>= (point) lim))
-         (setq first nil)
+         (setq first nil cookie-present nil)
          (unless (and level
                       (not (string-match
                             "\\<checkbox\\>"
@@ -9745,13 +11153,17 @@ statistics everywhere."
                (and (member kwd org-done-keywords)
                     (setq cnt-done (1+ cnt-done)))
                (outline-next-heading)))
-           (replace-match
-            (if is-percent
-                (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
-              (format "[%d/%d]" cnt-done cnt-all)))))
-       (when cookie-present
-         (run-hook-with-args 'org-after-todo-statistics-hook
-                             cnt-done (- cnt-all cnt-done)))))
+           (setq new
+                 (if is-percent
+                     (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
+                   (format "[%d/%d]" cnt-done cnt-all))
+                 ndel (- (match-end 0) (match-beginning 0)))
+           (goto-char (match-beginning 0))
+           (insert new)
+           (delete-region (point) (+ (point) ndel)))
+         (when cookie-present
+           (run-hook-with-args 'org-after-todo-statistics-hook
+                               cnt-done (- cnt-all cnt-done))))))
     (run-hooks 'org-todo-statistics-hook)))
 
 (defvar org-after-todo-statistics-hook nil
@@ -9772,7 +11184,7 @@ when there is a statistics cookie in the headline!
 
 (defvar org-todo-statistics-hook nil
   "Hook that is run whenever Org thinks TODO statistics should be updated.
-This hook runs even if there is no statisics cookie present, in which case
+This hook runs even if there is no statistics cookie present, in which case
 `org-after-todo-statistics-hook' would not run.")
 
 (defun org-todo-trigger-tag-changes (state)
@@ -9921,14 +11333,16 @@ Returns the new TODO keyword, or nil if no state change should occur."
             (throw 'exit t)))
       nil)))
 
-(defun org-get-repeat ()
+(defun org-get-repeat (&optional tagline)
   "Check if there is a deadline/schedule with repeater in this entry."
   (save-match-data
     (save-excursion
       (org-back-to-heading t)
-      (if (re-search-forward
-          org-repeat-re (save-excursion (outline-next-heading) (point)) t)
-         (match-string 1)))))
+      (and (re-search-forward (if tagline
+                                 (concat tagline "\\s-*" org-repeat-re)
+                               org-repeat-re)
+                             (org-entry-end-position) t)
+          (match-string-no-properties 1)))))
 
 (defvar org-last-changed-timestamp)
 (defvar org-last-inserted-timestamp)
@@ -9950,13 +11364,17 @@ This function is run automatically after each state change to a DONE state."
         (msg "Entry repeats: ")
         (org-log-done nil)
         (org-todo-log-states nil)
-        (nshiftmax 10) (nshift 0)
-        re type n what ts time)
+        re type n what ts time to-state)
     (when repeat
       (if (eq org-log-repeat t) (setq org-log-repeat 'state))
-      (org-todo (if (eq interpret 'type) last-state head))
-      (org-entry-put nil "LAST_REPEAT" (format-time-string
-                                       (org-time-stamp-format t t)))
+      (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
+                        org-todo-repeat-to-state))
+      (unless (and to-state (member to-state org-todo-keywords-1))
+       (setq to-state (if (eq interpret 'type) last-state head)))
+      (org-todo to-state)
+      (when (or org-log-repeat (org-entry-get nil "CLOCK"))
+       (org-entry-put nil "LAST_REPEAT" (format-time-string
+                                         (org-time-stamp-format t t))))
       (when org-log-repeat
        (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
                (memq 'org-add-log-note post-command-hook))
@@ -9992,15 +11410,17 @@ This function is run automatically after each state change to a DONE state."
               (- (time-to-days (current-time)) (time-to-days time))
               'day))
             ((equal (match-string 1 ts) "+")
-             (while (or (= nshift 0)
-                        (<= (time-to-days time) (time-to-days (current-time))))
-               (when (= (incf nshift) nshiftmax)
-                 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today.  Continue? " nshift))
-                     (error "Abort")))
-               (org-timestamp-change n (cdr (assoc what whata)))
-               (org-at-timestamp-p t)
-               (setq ts (match-string 1))
-               (setq time (save-match-data (org-time-string-to-time ts))))
+             (let ((nshiftmax 10) (nshift 0))
+               (while (or (= nshift 0)
+                          (<= (time-to-days time)
+                              (time-to-days (current-time))))
+                 (when (= (incf nshift) nshiftmax)
+                   (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today.  Continue? " nshift))
+                       (error "Abort")))
+                 (org-timestamp-change n (cdr (assoc what whata)))
+                 (org-at-timestamp-p t)
+                 (setq ts (match-string 1))
+                 (setq time (save-match-data (org-time-string-to-time ts)))))
              (org-timestamp-change (- n) (cdr (assoc what whata)))
              ;; rematch, so that we have everything in place for the real shift
              (org-at-timestamp-p t)
@@ -10041,13 +11461,36 @@ With argument REMOVE, remove any deadline from the item.
 When TIME is set, it should be an internal time specification, and the
 scheduling will use the corresponding date."
   (interactive "P")
-  (if remove
-      (progn
-       (org-remove-timestamp-with-keyword org-deadline-string)
-       (message "Item no longer has a deadline."))
-    (if (org-get-repeat)
-       (error "Cannot change deadline on task with repeater, please do that by hand")
+  (let* ((old-date (org-entry-get nil "DEADLINE"))
+        (repeater (and old-date
+                       (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
+                       (match-string 1 old-date))))
+    (if remove
+       (progn
+         (when (and old-date org-log-redeadline)
+           (org-add-log-setup 'deldeadline nil old-date 'findpos
+                              org-log-redeadline))
+         (org-remove-timestamp-with-keyword org-deadline-string)
+         (message "Item no longer has a deadline."))
       (org-add-planning-info 'deadline time 'closed)
+      (when (and old-date org-log-redeadline
+                (not (equal old-date
+                            (substring org-last-inserted-timestamp 1 -1))))
+       (org-add-log-setup 'redeadline nil old-date 'findpos
+                          org-log-redeadline))
+      (when repeater
+       (save-excursion
+         (org-back-to-heading t)
+         (when (re-search-forward (concat org-deadline-string " "
+                                          org-last-inserted-timestamp)
+                                  (save-excursion
+                                    (outline-next-heading) (point)) t)
+           (goto-char (1- (match-end 0)))
+           (insert " " repeater)
+           (setq org-last-inserted-timestamp
+                 (concat (substring org-last-inserted-timestamp 0 -1)
+                         " " repeater
+                         (substring org-last-inserted-timestamp -1))))))
       (message "Deadline on %s" org-last-inserted-timestamp))))
 
 (defun org-schedule (&optional remove time)
@@ -10056,13 +11499,36 @@ With argument REMOVE, remove any scheduling date from the item.
 When TIME is set, it should be an internal time specification, and the
 scheduling will use the corresponding date."
   (interactive "P")
-  (if remove
-      (progn
-       (org-remove-timestamp-with-keyword org-scheduled-string)
-       (message "Item is no longer scheduled."))
-    (if (org-get-repeat)
-       (error "Cannot reschedule task with repeater, please do that by hand")
+  (let* ((old-date (org-entry-get nil "SCHEDULED"))
+        (repeater (and old-date
+                       (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
+                       (match-string 1 old-date))))
+    (if remove
+       (progn
+         (when (and old-date org-log-reschedule)
+           (org-add-log-setup 'delschedule nil old-date 'findpos
+                              org-log-reschedule))
+         (org-remove-timestamp-with-keyword org-scheduled-string)
+         (message "Item is no longer scheduled."))
       (org-add-planning-info 'scheduled time 'closed)
+      (when (and old-date org-log-reschedule
+                (not (equal old-date
+                            (substring org-last-inserted-timestamp 1 -1))))
+       (org-add-log-setup 'reschedule nil old-date 'findpos
+                          org-log-reschedule))
+      (when repeater
+       (save-excursion
+         (org-back-to-heading t)
+         (when (re-search-forward (concat org-scheduled-string " "
+                                          org-last-inserted-timestamp)
+                                  (save-excursion
+                                    (outline-next-heading) (point)) t)
+           (goto-char (1- (match-end 0)))
+           (insert " " repeater)
+           (setq org-last-inserted-timestamp
+                 (concat (substring org-last-inserted-timestamp 0 -1)
+                         " " repeater
+                         (substring org-last-inserted-timestamp -1))))))
       (message "Scheduled to %s" org-last-inserted-timestamp))))
 
 (defun org-get-scheduled-time (pom &optional inherit)
@@ -10074,8 +11540,8 @@ returns nil."
       (apply 'encode-time (org-parse-time-string time)))))
 
 (defun org-get-deadline-time (pom &optional inherit)
-  "Get the deadine as a time tuple, of a format suitable for
-calling org-deadlin with, or if there is no scheduling, returns
+  "Get the deadline as a time tuple, of a format suitable for
+calling org-deadline with, or if there is no scheduling, returns
 nil."
   (let ((time (org-entry-get pom "DEADLINE" inherit)))
     (when time
@@ -10172,8 +11638,10 @@ be removed."
                             (re-search-forward org-closed-time-regexp nil t)))
                (replace-match "")
                (if (looking-at "--+<[^>]+>") (replace-match ""))
+               (skip-chars-backward " ")
                (if (looking-at " +") (replace-match ""))))
            (goto-char (point-max))
+           (and org-adapt-indentation (bolp) (org-indent-to-column col))
            (when what
              (insert
               (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
@@ -10190,7 +11658,7 @@ be removed."
              (end-of-line 1))
            (goto-char (point-min))
            (widen)
-           (if (and (looking-at "[ \t]+\n")
+           (if (and (looking-at "[ \t]*\n")
                     (equal (char-before) ?\n))
                (delete-region (1- (point)) (point-at-eol)))
            ts))))))
@@ -10215,7 +11683,7 @@ This is done in the same way as adding a state change note."
 
 (defvar org-property-end-re)
 (defun org-add-log-setup (&optional purpose state prev-state
-                                   findpos how &optional extra)
+                                   findpos how extra)
   "Set up the post command hook to take a note.
 If this is about to TODO state change, the new state is expected in STATE.
 When FINDPOS is non-nil, find the correct position for the note in
@@ -10276,10 +11744,11 @@ EXTRA is additional text that will be inserted into the notes buffer."
 (defun org-skip-over-state-notes ()
   "Skip past the list of State notes in an entry."
   (if (looking-at "\n[ \t]*- State") (forward-char 1))
-  (while (looking-at "[ \t]*- State")
-    (condition-case nil
-       (org-next-item)
-      (error (org-end-of-item)))))
+  (when (org-in-item-p)
+    (let ((limit (org-list-bottom-point)))
+      (while (looking-at "[ \t]*- State")
+       (goto-char (or (org-get-next-item (point) limit)
+                      (org-get-end-of-item limit)))))))
 
 (defun org-add-log-note (&optional purpose)
   "Pop up a window for taking a note, and add this note later at point."
@@ -10303,6 +11772,16 @@ EXTRA is additional text that will be inserted into the notes buffer."
                      (format "state change from \"%s\" to \"%s\""
                              (or org-log-note-previous-state "")
                              (or org-log-note-state "")))
+                    ((eq org-log-note-purpose 'reschedule)
+                     "rescheduling")
+                    ((eq org-log-note-purpose 'delschedule)
+                     "no longer scheduled")
+                    ((eq org-log-note-purpose 'redeadline)
+                     "changing deadline")
+                    ((eq org-log-note-purpose 'deldeadline)
+                     "removing deadline")
+                    ((eq org-log-note-purpose 'refile)
+                     "refiling")
                     ((eq org-log-note-purpose 'note)
                      "this entry")
                     (t (error "This should not happen")))))
@@ -10314,7 +11793,7 @@ EXTRA is additional text that will be inserted into the notes buffer."
   "Finish taking a log note, and insert it to where it belongs."
   (let ((txt (buffer-string))
        (note (cdr (assq org-log-note-purpose org-log-note-headings)))
-       lines ind)
+       lines ind bul)
     (kill-buffer (current-buffer))
     (while (string-match "\\`#.*\n[ \t\n]*" txt)
       (setq txt (replace-match "" t t txt)))
@@ -10330,6 +11809,9 @@ EXTRA is additional text that will be inserted into the notes buffer."
                   (cons "%t" (format-time-string
                               (org-time-stamp-format 'long 'inactive)
                               (current-time)))
+                  (cons "%T" (format-time-string
+                              (org-time-stamp-format 'long nil)
+                              (current-time)))
                   (cons "%s" (if org-log-note-state
                                  (concat "\"" org-log-note-state "\"")
                                ""))
@@ -10345,20 +11827,32 @@ EXTRA is additional text that will be inserted into the notes buffer."
         org-log-note-marker))
       (setq lines nil))
     (when lines
-      (save-excursion
-       (set-buffer (marker-buffer org-log-note-marker))
+      (with-current-buffer (marker-buffer org-log-note-marker)
        (save-excursion
          (goto-char org-log-note-marker)
          (move-marker org-log-note-marker nil)
          (end-of-line 1)
          (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
-         (insert "- " (pop lines))
-         (org-indent-line-function)
-         (beginning-of-line 1)
-         (looking-at "[ \t]*")
-         (setq ind (concat (match-string 0) "  "))
-         (end-of-line 1)
-         (while lines (insert "\n" ind (pop lines)))
+         (setq ind (save-excursion
+                     (if (org-in-item-p)
+                         (progn
+                           (goto-char (org-list-top-point))
+                           (org-get-indentation))
+                       (skip-chars-backward " \r\t\n")
+                       (cond
+                        ((and (org-at-heading-p)
+                              org-adapt-indentation)
+                         (1+ (org-current-level)))
+                        ((org-at-heading-p) 0)
+                        (t (org-get-indentation))))))
+         (setq bul (org-list-bullet-string "-"))
+         (org-indent-line-to ind)
+         (insert bul (pop lines))
+         (let ((ind-body (+ (length bul) ind)))
+           (while lines
+             (insert "\n")
+             (org-indent-line-to ind-body)
+             (insert (pop lines))))
          (message "Note stored")
          (org-back-to-heading t)
          (org-cycle-hide-drawers 'children)))))
@@ -10369,7 +11863,7 @@ EXTRA is additional text that will be inserted into the notes buffer."
   (and org-log-post-message (message "%s" org-log-post-message)))
 
 (defun org-remove-empty-drawer-at (drawer pos)
-  "Remove an emptyr DARWER drawer at position POS.
+  "Remove an empty drawer DRAWER at position POS.
 POS may also be a marker."
   (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
     (save-excursion
@@ -10385,17 +11879,18 @@ POS may also be a marker."
 This command can create sparse trees.  You first need to select the type
 of match used to create the tree:
 
-t      Show entries with a specific TODO keyword.
+t      Show all TODO entries.
+T      Show entries with a specific TODO keyword.
 m      Show entries selected by a tags/property match.
 p      Enter a property name and its value (both with completion on existing
        names/values) and show entries with that property.
-r      Show entries matching a regular expression.
+r      Show entries matching a regular expression (`/' can be used as well)
 d      Show deadlines due within `org-deadline-warning-days'.
 b      Show deadlines and scheduled items before a date.
 a      Show deadlines and scheduled items after a date."
   (interactive "P")
   (let (ans kwd value)
-    (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
+    (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n             [d]eadlines [b]efore-date [a]fter-date")
     (setq ans (read-char-exclusive))
     (cond
      ((equal ans ?d)
@@ -10405,6 +11900,8 @@ a      Show deadlines and scheduled items after a date."
      ((equal ans ?a)
       (call-interactively 'org-check-after-date))
      ((equal ans ?t)
+      (org-show-todo-tree nil))
+     ((equal ans ?T)
       (org-show-todo-tree '(4)))
      ((member ans '(?T ?m))
       (call-interactively 'org-match-sparse-tree))
@@ -10476,7 +11973,7 @@ that the match should indeed be shown."
     cnt))
 
 (defun org-show-context (&optional key)
-  "Make sure point and context and visible.
+  "Make sure point and context are visible.
 How much context is shown depends upon the variables
 `org-show-hierarchy-above', `org-show-following-heading'. and
 `org-show-siblings'."
@@ -10507,6 +12004,9 @@ How much context is shown depends upon the variables
            (org-flag-heading nil)
            (when siblings-p (org-show-siblings))))))))
 
+(defvar org-reveal-start-hook nil
+  "Hook run before revealing a location.")
+
 (defun org-reveal (&optional siblings)
   "Show current entry, hierarchy above it, and the following headline.
 This can be used to show a consistent set of context around locations
@@ -10515,17 +12015,26 @@ not t for the search context.
 
 With optional argument SIBLINGS, on each level of the hierarchy all
 siblings are shown.  This repairs the tree structure to what it would
-look like when opened with hierarchical calls to `org-cycle'."
+look like when opened with hierarchical calls to `org-cycle'.
+With double optional argument \\[universal-argument] \\[universal-argument], \
+go to the parent and show the
+entire tree."
   (interactive "P")
+  (run-hooks 'org-reveal-start-hook)
   (let ((org-show-hierarchy-above t)
        (org-show-following-heading t)
        (org-show-siblings (if siblings t org-show-siblings)))
-    (org-show-context nil)))
+    (org-show-context nil))
+  (when (equal siblings '(16))
+    (save-excursion
+      (when (org-up-heading-safe)
+       (org-show-subtree)
+       (run-hook-with-args 'org-cycle-hook 'subtree)))))
 
 (defun org-highlight-new-match (beg end)
   "Highlight from BEG to END and mark the highlight is an occur headline."
-  (let ((ov (org-make-overlay beg end)))
-    (org-overlay-put ov 'face 'secondary-selection)
+  (let ((ov (make-overlay beg end)))
+    (overlay-put ov 'face 'secondary-selection)
     (push ov org-occur-highlights)))
 
 (defun org-remove-occur-highlights (&optional beg end noremove)
@@ -10534,7 +12043,7 @@ BEG and END are ignored.  If NOREMOVE is nil, remove this function
 from the `before-change-functions' in the current buffer."
   (interactive)
   (unless org-inhibit-highlight-removal
-    (mapc 'org-delete-overlay org-occur-highlights)
+    (mapc 'delete-overlay org-occur-highlights)
     (setq org-occur-highlights nil)
     (setq org-occur-parameters nil)
     (unless noremove
@@ -10573,13 +12082,16 @@ ACTION can be `set', `up', `down', or a character."
                have t)
        (setq current org-default-priority))
       (cond
+       ((eq action 'remove)
+       (setq remove t new ?\ ))
        ((or (eq action 'set)
            (if (featurep 'xemacs) (characterp action) (integerp action)))
        (if (not (eq action 'set))
            (setq new action)
          (message "Priority %c-%c, SPC to remove: "
                   org-highest-priority org-lowest-priority)
-         (setq new (read-char-exclusive)))
+         (save-match-data
+           (setq new (read-char-exclusive))))
        (if (and (= (upcase org-highest-priority) org-highest-priority)
                 (= (upcase org-lowest-priority) org-lowest-priority))
            (setq new (upcase new)))
@@ -10623,18 +12135,20 @@ ACTION can be `set', `up', `down', or a character."
 
 (defun org-get-priority (s)
   "Find priority cookie and return priority."
-  (save-match-data
-    (if (not (string-match org-priority-regexp s))
-       (* 1000 (- org-lowest-priority org-default-priority))
-      (* 1000 (- org-lowest-priority
-                (string-to-char (match-string 2 s)))))))
+  (if (functionp org-get-priority-function)
+      (funcall org-get-priority-function)
+    (save-match-data
+      (if (not (string-match org-priority-regexp s))
+         (* 1000 (- org-lowest-priority org-default-priority))
+       (* 1000 (- org-lowest-priority
+                  (string-to-char (match-string 2 s))))))))
 
 ;;;; Tags
 
 (defvar org-agenda-archives-mode)
 (defvar org-map-continue-from nil
   "Position from where mapping should continue.
-Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
+Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
 
 (defvar org-scanner-tags nil
   "The current tag list while the tags scanner is running.")
@@ -10664,14 +12178,13 @@ only lines with a TODO keyword are included in the output."
   (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
                     (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
                     (org-re
-                     "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
+                     "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
         (props (list 'face 'default
                      'done-face 'org-agenda-done
                      'undone-face 'default
                      '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"
                              (abbreviate-file-name
@@ -10865,11 +12378,11 @@ also TODO lines."
 
   ;; Parse the string and create a lisp form
   (let ((match0 match)
-       (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
+       (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
        minus tag mm
        tagsmatch todomatch tagsmatcher todomatcher kwd matcher
        orterms term orlist re-p str-p level-p level-op time-p
-       prop-p pn pv po cat-p gv rest)
+       prop-p pn pv po gv rest)
     (if (string-match "/+" match)
        ;; match contains also a todo-matching request
        (progn
@@ -10893,7 +12406,9 @@ also TODO lines."
          (setq rest (substring term (match-end 0))
                minus (and (match-end 1)
                           (equal (match-string 1 term) "-"))
-               tag (match-string 2 term)
+               tag (save-match-data (replace-regexp-in-string
+                                     "\\\\-" "-"
+                                     (match-string 2 term)))
                re-p (equal (string-to-char tag) ?{)
                level-p (match-end 4)
                prop-p (match-end 5)
@@ -10907,7 +12422,6 @@ also TODO lines."
                     (setq pn (match-string 5 term)
                           po (match-string 6 term)
                           pv (match-string 7 term)
-                          cat-p (equal pn "CATEGORY")
                           re-p (equal (string-to-char pv) ?{)
                           str-p (equal (string-to-char pv) ?\")
                           time-p (save-match-data
@@ -11036,7 +12550,7 @@ epoch to the beginning of today (00:00)."
   (delq nil list))
 
 (defvar org-add-colon-after-tag-completion nil)  ;; dynamically scoped param
-(defvar org-tags-overlay (org-make-overlay 1 1))
+(defvar org-tags-overlay (make-overlay 1 1))
 (org-detach-overlay org-tags-overlay)
 
 (defun org-get-local-tags-at (&optional pos)
@@ -11072,7 +12586,7 @@ ignore inherited ones."
                    (while (not (equal lastpos (point)))
                      (setq lastpos (point))
                      (when (looking-at
-                            (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
+                            (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
                        (setq ltags (org-split-string
                                     (org-match-string-no-properties 1) ":"))
                        (when parent
@@ -11099,7 +12613,7 @@ If ONOFF is `on' or `off', don't toggle but set to this state."
   (let (res current)
     (save-excursion
       (org-back-to-heading t)
-      (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
+      (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
                             (point-at-eol) t)
          (progn
            (setq current (match-string 1))
@@ -11129,7 +12643,7 @@ If ONOFF is `on' or `off', don't toggle but set to this state."
   ;; Assumes that this is a headline
   (let ((pos (point)) (col (current-column)) ncol tags-l p)
     (beginning-of-line 1)
-    (if        (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
+    (if        (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
             (< pos (match-beginning 2)))
        (progn
          (setq tags-l (- (match-end 2) (match-beginning 2)))
@@ -11157,6 +12671,49 @@ If ONOFF is `on' or `off', don't toggle but set to this state."
       (org-back-to-heading t)
       (org-set-tags arg just-align))))
 
+(defun org-set-tags-to (data)
+  "Set the tags of the current entry to DATA, replacing the current tags.
+DATA may be a tags string like :aa:bb:cc:, or a list of tags.
+If DATA is nil or the empty string, any tags will be removed."
+  (interactive "sTags: ")
+  (setq data
+       (cond
+        ((eq data nil) "")
+        ((equal data "") "")
+        ((stringp data)
+         (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
+                 ":"))
+        ((listp data)
+         (concat ":" (mapconcat 'identity data ":") ":"))
+        (t nil)))
+  (when data
+    (save-excursion
+      (org-back-to-heading t)
+      (when (looking-at org-complex-heading-regexp)
+       (if (match-end 5)
+           (progn
+             (goto-char (match-beginning 5))
+             (insert data)
+             (delete-region (point) (point-at-eol))
+             (org-set-tags nil 'align))
+         (goto-char (point-at-eol))
+         (insert " " data)
+         (org-set-tags nil 'align)))
+      (beginning-of-line 1)
+      (if (looking-at ".*?\\([ \t]+\\)$")
+         (delete-region (match-beginning 1) (match-end 1))))))
+
+(defun org-align-all-tags ()
+  "Align the tags i all headings."
+  (interactive)
+  (save-excursion
+    (or (ignore-errors (org-back-to-heading t))
+       (outline-next-heading))
+    (if (org-on-heading-p)
+       (org-set-tags t)
+      (message "No headings"))))
+
+(defvar org-indent-indentation-per-level)
 (defun org-set-tags (&optional arg just-align)
   "Set the tags for the current headline.
 With prefix ARG, realign all tags in headings in the current buffer."
@@ -11166,7 +12723,7 @@ With prefix ARG, realign all tags in headings in the current buffer."
         (col (current-column))
         (org-setting-tags t)
         table current-tags inherited-tags ; computed below when needed
-        tags p0 c0 c1 rpl)
+        tags p0 c0 c1 rpl di tc level)
     (if arg
        (save-excursion
          (goto-char (point-min))
@@ -11180,7 +12737,11 @@ With prefix ARG, realign all tags in headings in the current buffer."
        ;; Get a new set of tags from the user
        (save-excursion
          (setq table (append org-tag-persistent-alist
-                             (or org-tag-alist (org-get-buffer-tags)))
+                             (or org-tag-alist (org-get-buffer-tags))
+                             (and
+                              org-complete-tags-always-offer-all-agenda-tags
+                              (org-global-tags-completion-table
+                               (org-agenda-files))))
                org-last-tags-completion-table table
                current-tags (org-split-string current ":")
                inherited-tags (nreverse
@@ -11192,19 +12753,24 @@ With prefix ARG, realign all tags in headings in the current buffer."
                             (delq nil (mapcar 'cdr table))))
                    (org-fast-tag-selection
                     current-tags inherited-tags table
-                    (if org-fast-tag-selection-include-todo org-todo-key-alist))
+                    (if org-fast-tag-selection-include-todo
+                        org-todo-key-alist))
                  (let ((org-add-colon-after-tag-completion t))
                    (org-trim
                     (org-without-partial-completion
-                     (org-icompleting-read "Tags: " 'org-tags-completion-function
+                     (org-icompleting-read "Tags: "
+                                           'org-tags-completion-function
                                       nil nil current 'org-tags-history)))))))
        (while (string-match "[-+&]+" tags)
          ;; No boolean logic, just a list
          (setq tags (replace-match ":" t t tags))))
 
+      (setq tags (replace-regexp-in-string "[ ,]" ":" tags))
+
       (if org-tags-sort-function
          (setq tags (mapconcat 'identity
-                               (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
+                               (sort (org-split-string
+                                      tags (org-re "[^[:alnum:]_@#%]+"))
                                      org-tags-sort-function) ":")))
 
       (if (string-match "\\`[\t ]*\\'" tags)
@@ -11214,6 +12780,9 @@ With prefix ARG, realign all tags in headings in the current buffer."
 
       ;; Insert new tags at the correct column
       (beginning-of-line 1)
+      (setq level (or (and (looking-at org-outline-regexp)
+                          (- (match-end 0) (point) 1))
+                     1))
       (cond
        ((and (equal current "") (equal tags "")))
        ((re-search-forward
@@ -11222,10 +12791,14 @@ With prefix ARG, realign all tags in headings in the current buffer."
        (if (equal tags "")
            (setq rpl "")
          (goto-char (match-beginning 0))
-         (setq c0 (current-column) p0 (point)
-               c1 (max (1+ c0) (if (> org-tags-column 0)
-                                   org-tags-column
-                                 (- (- org-tags-column) (length tags))))
+         (setq c0 (current-column)
+               ;; compute offset for the case of org-indent-mode active
+               di (if org-indent-mode
+                      (* (1- org-indent-indentation-per-level) (1- level))
+                    0)
+               p0 (if (equal (char-before) ?*) (1+ (point)) (point))
+               tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
+               c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
                rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
        (replace-match rpl t t)
        (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
@@ -11277,7 +12850,7 @@ This works in the agenda, and also in an org-mode buffer."
 (defun org-tags-completion-function (string predicate &optional flag)
   (let (s1 s2 rtn (ctable org-last-tags-completion-table)
           (confirm (lambda (x) (stringp (car x)))))
-    (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
+    (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
         (setq s1 (match-string 1 string)
               s2 (match-string 2 string))
       (setq s1 "" s2 string))
@@ -11325,6 +12898,7 @@ This works in the agenda, and also in an org-mode buffer."
       (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
       (org-overlay-display org-tags-overlay (concat prefix s)))))
 
+(defvar org-last-tag-selection-key nil)
 (defun org-fast-tag-selection (current inherited table &optional todo-table)
   "Fast tag selection with single keys.
 CURRENT is the current list of tags in the headline, INHERITED is the
@@ -11353,7 +12927,7 @@ Returns the new tags string, or nil to not change the current settings."
     (save-excursion
       (beginning-of-line 1)
       (if (looking-at
-          (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
+          (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
          (setq ov-start (match-beginning 1)
                ov-end (match-end 1)
                ov-prefix "")
@@ -11366,7 +12940,7 @@ Returns the new tags string, or nil to not change the current settings."
               (if (> (current-column) org-tags-column)
                   " "
                 (make-string (- org-tags-column (current-column)) ?\ ))))))
-    (org-move-overlay org-tags-overlay ov-start ov-end)
+    (move-overlay org-tags-overlay ov-start ov-end)
     (save-window-excursion
       (if expert
          (set-buffer (get-buffer-create " *Org tags*"))
@@ -11382,15 +12956,15 @@ Returns the new tags string, or nil to not change the current settings."
       (setq tbl fulltable char ?a cnt 0)
       (while (setq e (pop tbl))
        (cond
-        ((equal e '(:startgroup))
+        ((equal (car e) :startgroup)
          (push '() groups) (setq ingroup t)
          (when (not (= cnt 0))
            (setq cnt 0)
            (insert "\n"))
-         (insert "{ "))
-        ((equal e '(:endgroup))
+         (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
+        ((equal (car e) :endgroup)
          (setq ingroup nil cnt 0)
-         (insert "}\n"))
+         (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
         ((equal e '(:newline))
          (when (not (= cnt 0))
            (setq cnt 0)
@@ -11435,10 +13009,11 @@ Returns the new tags string, or nil to not change the current settings."
       (setq rtn
            (catch 'exit
              (while t
-               (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
-                        (if groups " [!] no groups" " [!]groups")
+               (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
+                        (if (not groups) "no " "")
                         (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
                (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
+               (setq org-last-tag-selection-key c)
                (cond
                 ((= c ?\r) (throw 'exit t))
                 ((= c ?!)
@@ -11502,7 +13077,7 @@ Returns the new tags string, or nil to not change the current settings."
                (org-fast-tag-insert "Current" current c-face)
                (org-set-current-tags-overlay current ov-prefix)
                (while (re-search-forward
-                       (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
+                       (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
                  (setq tg (match-string 1))
                  (add-text-properties
                   (match-beginning 1) (match-end 1)
@@ -11523,7 +13098,7 @@ Returns the new tags string, or nil to not change the current settings."
     (error "Not on a heading"))
   (save-excursion
     (beginning-of-line 1)
-    (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
+    (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
        (org-match-string-no-properties 1)
       "")))
 
@@ -11537,10 +13112,11 @@ Returns the new tags string, or nil to not change the current settings."
     (save-excursion
       (goto-char (point-min))
       (while (re-search-forward
-             (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
+             (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
        (when (equal (char-after (point-at-bol 0)) ?*)
          (mapc (lambda (x) (add-to-list 'tags x))
                (org-split-string (org-match-string-no-properties 1) ":")))))
+    (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
     (mapcar 'list tags)))
 
 ;;;; The mapping API
@@ -11590,7 +13166,7 @@ the scanner.  The following items can be given here:
   comment    skip trees with the COMMENT keyword
   function or Emacs Lisp form:
              will be used as value for `org-agenda-skip-function', so whenever
-             the the function returns t, FUNC will not be called for that
+             the function returns t, FUNC will not be called for that
              entry and search will continue from the point where the
              function leaves it.
 
@@ -11612,6 +13188,7 @@ a *different* entry, you cannot use these techniques."
         org-todo-keywords-for-agenda
         org-done-keywords-for-agenda
         org-todo-keyword-alist-for-agenda
+        org-drawers-for-agenda
         org-tag-alist-for-agenda)
 
     (cond
@@ -11660,7 +13237,7 @@ a *different* entry, you cannot use these techniques."
 
 (defconst org-special-properties
   '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
-    "TIMESTAMP" "TIMESTAMP_IA")
+    "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
   "The special properties valid in Org-mode.
 
 These are properties that are not defined in the property drawer,
@@ -11671,8 +13248,8 @@ but in some other way.")
     "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
     "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
     "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
-    "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
-    "CLOCK_MODELINE_TOTAL")
+    "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
+    "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
   "Some properties that are used by Org-mode for various purposes.
 Being in this list makes sure that they are offered for completion.")
 
@@ -11680,7 +13257,7 @@ Being in this list makes sure that they are offered for completion.")
   "Regular expression matching the first line of a property drawer.")
 
 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
-  "Regular expression matching the first line of a property drawer.")
+  "Regular expression matching the last line of a property drawer.")
 
 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
   "Regular expression matching the first line of a property drawer.")
@@ -11727,17 +13304,28 @@ allowed value."
         (cur (org-entry-get nil prop))
         (allowed (org-property-get-allowed-values nil prop 'table))
         (existing (mapcar 'list (org-property-values prop)))
+        rpl
         (val (cond
               ((stringp value) value)
               ((and allowed (integerp value))
                (or (car (nth (1- value) allowed))
                    (car (org-last allowed))))
               (allowed
-               (org-completing-read "Value: " allowed nil 'req-match))
+               (message "Select 1-9,0, [RET%s]: %s"
+                        (if cur (concat "=" cur) "")
+                        (mapconcat 'car allowed " "))
+               (setq rpl (read-char-exclusive))
+               (if (equal rpl ?\r)
+                   cur
+                 (setq rpl (- rpl ?0))
+                 (if (equal rpl 0) (setq rpl 10))
+                 (if (and (> rpl 0) (<= rpl (length allowed)))
+                     (car (nth (1- rpl) allowed))
+                   (org-completing-read "Effort: " allowed nil))))
               (t
                (let (org-completion-use-ido org-completion-use-iswitchb)
                  (org-completing-read
-                  (concat "Value " (if (and cur (string-match "\\S-" cur))
+                  (concat "Effort " (if (and cur (string-match "\\S-" cur))
                                        (concat "[" cur "]") "")
                           ": ")
                   existing nil nil "" nil cur))))))
@@ -11746,13 +13334,15 @@ allowed value."
     (message "%s is now %s" prop val)))
 
 (defun org-at-property-p ()
-  "Is the cursor in a property line?"
-  ;; FIXME: Does not check if we are actually in the drawer.
-  ;; FIXME: also returns true on any drawers.....
-  ;; This is used by C-c C-c for property action.
+  "Is cursor inside a property drawer?"
   (save-excursion
     (beginning-of-line 1)
-    (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
+    (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
+      (save-match-data ;; Used by calling procedures
+       (let ((p (point))
+             (range (unless (org-before-first-heading-p)
+                      (org-get-property-block))))
+         (and range (<= (car range) p) (< p (cdr range))))))))
 
 (defun org-get-property-block (&optional beg end force)
   "Return the (beg . end) range of the body of the property drawer.
@@ -11783,7 +13373,7 @@ If the drawer does not exist and FORCE is non-nil, create the drawer."
          (insert ":END:\n"))
        (cons beg end)))))
 
-(defun org-entry-properties (&optional pom which)
+(defun org-entry-properties (&optional pom which specific)
   "Get all properties of the entry at point-or-marker POM.
 This includes the TODO keyword, the tags, time strings for deadline,
 scheduled, and clocking, and any additional properties defined in the
@@ -11791,12 +13381,16 @@ entry.  The return value is an alist, keys may occur multiple times
 if the property key was used several times.
 POM may also be nil, in which case the current entry is used.
 If WHICH is nil or `all', get all properties.  If WHICH is
-`special' or `standard', only get that subclass."
+`special' or `standard', only get that subclass.  If WHICH
+is a string only get exactly this property.  SPECIFIC can be a string, the
+specific property we are interested in.  Specifying it can speed
+things up because then unnecessary parsing is avoided."
   (setq which (or which 'all))
   (org-with-point-at pom
     (let ((clockstr (substring org-clock-string 0 -1))
-         (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
-         beg end range props sum-props key value string clocksum)
+         (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
+         (case-fold-search nil)
+         beg end range props sum-props key key1 value string clocksum)
       (save-excursion
        (when (condition-case nil
                  (and (org-mode-p) (org-back-to-heading t))
@@ -11809,31 +13403,53 @@ If WHICH is nil or `all', get all properties.  If WHICH is
          (when (memq which '(all special))
            ;; Get the special properties, like TODO and tags
            (goto-char beg)
-           (when (and (looking-at org-todo-line-regexp) (match-end 2))
+           (when (and (or (not specific) (string= specific "TODO"))
+                      (looking-at org-todo-line-regexp) (match-end 2))
              (push (cons "TODO" (org-match-string-no-properties 2)) props))
-           (when (looking-at org-priority-regexp)
+           (when (and (or (not specific) (string= specific "PRIORITY"))
+                      (looking-at org-priority-regexp))
              (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
-           (when (and (setq value (org-get-tags-string))
+           (when (and (or (not specific) (string= specific "TAGS"))
+                      (setq value (org-get-tags-string))
                       (string-match "\\S-" value))
              (push (cons "TAGS" value) props))
-           (when (setq value (org-get-tags-at))
-             (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
+           (when (and (or (not specific) (string= specific "ALLTAGS"))
+                      (setq value (org-get-tags-at)))
+             (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
+                                           ":"))
                    props))
-           (while (re-search-forward org-maybe-keyword-time-regexp end t)
-             (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
-                   string (if (equal key clockstr)
-                              (org-no-properties
-                               (org-trim
-                                (buffer-substring
-                                 (match-beginning 3) (goto-char (point-at-eol)))))
-                            (substring (org-match-string-no-properties 3) 1 -1)))
-             (unless key
-               (if (= (char-after (match-beginning 3)) ?\[)
-                   (setq key "TIMESTAMP_IA")
-                 (setq key "TIMESTAMP")))
-             (when (or (equal key clockstr) (not (assoc key props)))
-               (push (cons key string) props)))
-
+           (when (or (not specific) (string= specific "BLOCKED"))
+             (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
+           (when (or (not specific)
+                     (member specific
+                             '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
+                               "TIMESTAMP" "TIMESTAMP_IA")))
+             (while (re-search-forward org-maybe-keyword-time-regexp end t)
+               (setq key (if (match-end 1)
+                             (substring (org-match-string-no-properties 1)
+                                        0 -1))
+                     string (if (equal key clockstr)
+                                (org-no-properties
+                                 (org-trim
+                                  (buffer-substring
+                                   (match-beginning 3) (goto-char
+                                                        (point-at-eol)))))
+                              (substring (org-match-string-no-properties 3)
+                                         1 -1)))
+               ;; Get the correct property name from the key.  This is
+               ;; necessary if the user has configured time keywords.
+               (setq key1 (concat key ":"))
+               (cond
+                ((not key)
+                 (setq key
+                       (if (= (char-after (match-beginning 3)) ?\[)
+                           "TIMESTAMP_IA" "TIMESTAMP")))
+                ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
+                ((equal key1 org-deadline-string)  (setq key "DEADLINE"))
+                ((equal key1 org-closed-string)    (setq key "CLOSED"))
+                ((equal key1 org-clock-string)     (setq key "CLOCK")))
+               (when (or (equal key "CLOCK") (not (assoc key props)))
+                 (push (cons key string) props))))
            )
 
          (when (memq which '(all standard))
@@ -11860,22 +13476,27 @@ If WHICH is nil or `all', get all properties.  If WHICH is
            (push (cons "CATEGORY" value) props))
          (append sum-props (nreverse props)))))))
 
-(defun org-entry-get (pom property &optional inherit)
+(defun org-entry-get (pom property &optional inherit literal-nil)
   "Get value of PROPERTY for entry at point-or-marker POM.
 If INHERIT is non-nil and the entry does not have the property,
 then also check higher levels of the hierarchy.
 If INHERIT is the symbol `selective', use inheritance only if the setting
 in `org-use-property-inheritance' selects PROPERTY for inheritance.
 If the property is present but empty, the return value is the empty string.
-If the property is not present at all, nil is returned."
+If the property is not present at all, nil is returned.
+
+If LITERAL-NIL is set, return the string value \"nil\" as a string,
+do not interpret it as the list atom nil.  This is used for inheritance
+when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
   (org-with-point-at pom
     (if (and inherit (if (eq inherit 'selective)
                         (org-property-inherit-p property)
                       t))
-       (org-entry-get-with-inheritance property)
+       (org-entry-get-with-inheritance property literal-nil)
       (if (member property org-special-properties)
-         ;; We need a special property.  Use brute force, get all properties.
-         (cdr (assoc property (org-entry-properties nil 'special)))
+         ;; We need a special property.  Use `org-entry-properties' to
+         ;; retrieve it, but specify the wanted property
+         (cdr (assoc property (org-entry-properties nil 'special property)))
        (let ((range (org-get-property-block)))
          (if (and range
                   (goto-char (car range))
@@ -11884,7 +13505,9 @@ If the property is not present at all, nil is returned."
                    (cdr range) t))
              ;; Found the property, return it.
              (if (match-end 1)
-                 (org-match-string-no-properties 1)
+                 (if literal-nil
+                     (org-match-string-no-properties 1)
+                   (org-not-nil (org-match-string-no-properties 1)))
                "")))))))
 
 (defun org-property-or-variable-value (var &optional inherit)
@@ -11979,8 +13602,12 @@ no match, the marker will point nowhere.
 Note that also `org-entry-get' calls this function, if the INHERIT flag
 is set.")
 
-(defun org-entry-get-with-inheritance (property)
-  "Get entry property, and search higher levels if not present."
+(defun org-entry-get-with-inheritance (property &optional literal-nil)
+  "Get entry property, and search higher levels if not present.
+The search will stop at the first ancestor which has the property defined.
+If the value found is \"nil\", return nil to show that the property
+should be considered as undefined (this is the meaning of nil here).
+However, if LITERAL-NIL is set, return the string value \"nil\" instead."
   (move-marker org-entry-property-inherited-from nil)
   (let (tmp)
     (save-excursion
@@ -11988,15 +13615,21 @@ is set.")
        (widen)
        (catch 'ex
          (while t
-           (when (setq tmp (org-entry-get nil property))
+           (when (setq tmp (org-entry-get nil property nil 'literal-nil))
              (org-back-to-heading t)
              (move-marker org-entry-property-inherited-from (point))
              (throw 'ex tmp))
            (or (org-up-heading-safe) (throw 'ex nil)))))
-      (or tmp
-         (cdr (assoc property org-file-properties))
-         (cdr (assoc property org-global-properties))
-         (cdr (assoc property org-global-properties-fixed))))))
+      (setq tmp (or tmp
+                   (cdr (assoc property org-file-properties))
+                   (cdr (assoc property org-global-properties))
+                   (cdr (assoc property org-global-properties-fixed))))
+      (if literal-nil tmp (org-not-nil tmp)))))
+
+(defvar org-property-changed-functions nil
+  "Hook called when the value of a property has changed.
+Each hook function should accept two arguments, the name of the property
+and the new value.")
 
 (defun org-entry-put (pom property value)
   "Set PROPERTY to VALUE for entry at point-or-marker POM."
@@ -12050,7 +13683,8 @@ is set.")
            (org-indent-line-function)
            (insert ":" property ":"))
          (and value (insert " " value))
-         (org-indent-line-function)))))))
+         (org-indent-line-function)))))
+    (run-hook-with-args 'org-property-changed-functions property value)))
 
 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
   "Get all property keys in the current buffer.
@@ -12170,16 +13804,17 @@ in the current file."
                                          keys)))
                      prop0)))
          (cur (org-entry-get nil prop))
+         (prompt (concat prop " value"
+                         (if (and cur (string-match "\\S-" cur))
+                             (concat " [" cur "]") "") ": "))
          (allowed (org-property-get-allowed-values nil prop 'table))
          (existing (mapcar 'list (org-property-values prop)))
          (val (if allowed
-                  (org-completing-read "Value: " allowed nil 'req-match)
+                  (org-completing-read prompt allowed nil
+                     (not (get-text-property 0 'org-unrestricted
+                                             (caar allowed))))
                 (let (org-completion-use-ido org-completion-use-iswitchb)
-                  (org-completing-read
-                   (concat "Value " (if (and cur (string-match "\\S-" cur))
-                                       (concat "[" cur "]") "")
-                           ": ")
-                   existing nil nil "" nil cur)))))
+                  (org-completing-read prompt existing nil nil "" nil cur)))))
      (list prop (if (equal val "") cur val))))
   (unless (equal (org-entry-get nil property) value)
     (org-entry-put nil property value)))
@@ -12188,8 +13823,8 @@ in the current file."
   "In the current entry, delete PROPERTY."
   (interactive
    (let* ((completion-ignore-case t)
-         (prop (org-icompleting-read
-                "Property: " (org-entry-properties nil 'standard))))
+         (prop (org-icompleting-read "Property: "
+                                     (org-entry-properties nil 'standard))))
      (list prop)))
   (message "Property %s %s" property
           (if (org-entry-delete nil property)
@@ -12231,6 +13866,15 @@ then applies it to the property in the column format's scope."
       (error "No operator defined for property %s" prop))
     (org-columns-compute prop)))
 
+(defvar org-property-allowed-value-functions nil
+  "Hook for functions supplying allowed values for a specific property.
+The functions must take a single argument, the name of the property, and
+return a flat list of allowed values.  If \":ETC\" is one of
+the values, this means that these values are intended as defaults for
+completion, but that other values should be allowed too.
+The functions must return nil if they are not responsible for this
+property.")
+
 (defun org-property-get-allowed-values (pom property &optional table)
   "Get allowed values for the property PROPERTY.
 When TABLE is non-nil, return an alist that can directly be used for
@@ -12246,9 +13890,10 @@ completion."
          (push (char-to-string n) vals)
          (setq n (1- n)))))
      ((member property org-special-properties))
+     ((setq vals (run-hook-with-args-until-success
+                 'org-property-allowed-value-functions property)))
      (t
       (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
-
       (when (and vals (string-match "\\S-" vals))
        (setq vals (car (read-from-string (concat "(" vals ")"))))
        (setq vals (mapcar (lambda (x)
@@ -12257,6 +13902,9 @@ completion."
                                   ((symbolp x) (symbol-name x))
                                   (t "???")))
                           vals)))))
+    (when (member ":ETC" vals)
+      (setq vals (remove ":ETC" vals))
+      (org-add-props (car vals) '(org-unrestricted t)))
     (if table (mapcar 'list vals) vals)))
 
 (defun org-property-previous-allowed-value (&optional previous)
@@ -12287,7 +13935,89 @@ completion."
     (replace-match (concat " :" key ": " nval) t t)
     (org-indent-line-function)
     (beginning-of-line 1)
-    (skip-chars-forward " \t")))
+    (skip-chars-forward " \t")
+    (run-hook-with-args 'org-property-changed-functions key nval)))
+
+(defun org-find-olp (path &optional this-buffer)
+  "Return a marker pointing to the entry at outline path OLP.
+If anything goes wrong, throw an error.
+You can wrap this call to catch the error like this:
+
+  (condition-case msg
+      (org-mobile-locate-entry (match-string 4))
+    (error (nth 1 msg)))
+
+The return value will then be either a string with the error message,
+or a marker if everything is OK.
+
+If THIS-BUFFER is set, the outline path does not contain a file,
+only headings."
+  (let* ((file (if this-buffer buffer-file-name (pop path)))
+        (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
+        (level 1)
+        (lmin 1)
+        (lmax 1)
+        limit re end found pos heading cnt)
+    (unless buffer (error "File not found :%s" file))
+    (with-current-buffer buffer
+      (save-excursion
+       (save-restriction
+         (widen)
+         (setq limit (point-max))
+         (goto-char (point-min))
+         (while (setq heading (pop path))
+           (setq re (format org-complex-heading-regexp-format
+                            (regexp-quote heading)))
+           (setq cnt 0 pos (point))
+           (while (re-search-forward re end t)
+             (setq level (- (match-end 1) (match-beginning 1)))
+             (if (and (>= level lmin) (<= level lmax))
+                 (setq found (match-beginning 0) cnt (1+ cnt))))
+           (when (= cnt 0) (error "Heading not found on level %d: %s"
+                                  lmax heading))
+           (when (> cnt 1) (error "Heading not unique on level %d: %s"
+                                  lmax heading))
+           (goto-char found)
+           (setq lmin (1+ level) lmax (+ lmin (if org-odd-levels-only 1 0)))
+           (setq end (save-excursion (org-end-of-subtree t t))))
+         (when (org-on-heading-p)
+           (move-marker (make-marker) (point))))))))
+
+(defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
+  "Find node HEADING in BUFFER.
+Return a marker to the heading if it was found, or nil if not.
+If POS-ONLY is set, return just the position instead of a marker.
+
+The heading text must match exact, but it may have a TODO keyword,
+a priority cookie and tags in the standard locations."
+  (with-current-buffer (or buffer (current-buffer))
+    (save-excursion
+      (save-restriction
+       (widen)
+       (goto-char (point-min))
+       (let (case-fold-search)
+         (if (re-search-forward
+              (format org-complex-heading-regexp-format
+                      (regexp-quote heading)) nil t)
+             (if pos-only
+                 (match-beginning 0)
+               (move-marker (make-marker) (match-beginning 0)))))))))
+
+(defun org-find-exact-heading-in-directory (heading &optional dir)
+  "Find Org node headline HEADING in all .org files in directory DIR.
+When the target headline is found, return a marker to this location."
+  (let ((files (directory-files (or dir default-directory)
+                               nil "\\`[^.#].*\\.org\\'"))
+        file visiting m buffer)
+    (catch 'found
+      (while (setq file (pop files))
+        (message "trying %s" file)
+        (setq visiting (org-find-base-buffer-visiting file))
+        (setq buffer (or visiting (find-file-noselect file)))
+        (setq m (org-find-exact-headline-in-buffer
+                 heading buffer))
+        (when (and (not m) (not visiting)) (kill-buffer buffer))
+        (and m (throw 'found m))))))
 
 (defun org-find-entry-with-id (ident)
   "Locate the entry that contains the ID property with exact value IDENT.
@@ -12395,8 +14125,8 @@ So these are more for recording a certain time/date."
   (interactive "P")
   (org-time-stamp arg 'inactive))
 
-(defvar org-date-ovl (org-make-overlay 1 1))
-(org-overlay-put org-date-ovl 'face 'org-warning)
+(defvar org-date-ovl (make-overlay 1 1))
+(overlay-put org-date-ovl 'face 'org-warning)
 (org-detach-overlay org-date-ovl)
 
 (defvar org-ans1) ; dynamically scoped parameter
@@ -12417,10 +14147,15 @@ The prompt will suggest to enter an ISO date, but you can also enter anything
 which will at least partially be understood by `parse-time-string'.
 Unrecognized parts of the date will default to the current day, month, year,
 hour and minute.  If this command is called to replace a timestamp at point,
-of to enter the second timestamp of a range, the default time is taken from the
-existing stamp.  For example,
+of to enter the second timestamp of a range, the default time is taken
+from the existing stamp.  Furthermore, the command prefers the future,
+so if you are giving a date where the year is not given, and the day-month
+combination is already past in the current year, it will assume you
+mean next year.  For details, see the manual.  A few examples:
+
   3-2-5         --> 2003-02-05
   feb 15        --> currentyear-02-15
+  2/15          --> currentyear-02-15
   sep 12 9      --> 2009-09-12
   12:45         --> today 12:45
   22 sept 0:34  --> currentyear-09-22 0:34
@@ -12473,11 +14208,10 @@ user."
                    (setq def (apply 'encode-time defdecode)
                          defdecode (decode-time def)))))
         (calendar-frame-setup nil)
+        (calendar-setup nil)
         (calendar-move-hook nil)
         (calendar-view-diary-initially-flag nil)
-        (view-diary-entries-initially nil)
         (calendar-view-holidays-initially-flag nil)
-        (view-calendar-holidays-initially nil)
         (timestr (format-time-string
                   (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
         (prompt (concat (if prompt (concat prompt " ") "")
@@ -12498,10 +14232,8 @@ user."
                 (map (copy-keymap calendar-mode-map))
                 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
            (org-defkey map (kbd "RET") 'org-calendar-select)
-           (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
-                       'org-calendar-select-mouse)
-           (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
-                       'org-calendar-select-mouse)
+           (org-defkey map [mouse-1] 'org-calendar-select-mouse)
+           (org-defkey map [mouse-2] 'org-calendar-select-mouse)
            (org-defkey minibuffer-local-map [(meta shift left)]
                        (lambda () (interactive)
                          (org-eval-in-calendar '(calendar-backward-month 1))))
@@ -12544,6 +14276,14 @@ user."
            (org-defkey minibuffer-local-map "<"
                        (lambda () (interactive)
                          (org-eval-in-calendar '(scroll-calendar-right 1))))
+           (org-defkey minibuffer-local-map "\C-v"
+                       (lambda () (interactive)
+                         (org-eval-in-calendar
+                          '(calendar-scroll-left-three-months 1))))
+           (org-defkey minibuffer-local-map "\M-v"
+                       (lambda () (interactive)
+                         (org-eval-in-calendar
+                          '(calendar-scroll-right-three-months 1))))
            (run-hooks 'org-read-date-minibuffer-setup-hook)
            (unwind-protect
                (progn
@@ -12558,7 +14298,7 @@ user."
              (remove-hook 'post-command-hook 'org-read-date-display)
              (use-local-map old-map)
              (when org-read-date-overlay
-               (org-delete-overlay org-read-date-overlay)
+               (delete-overlay org-read-date-overlay)
                (setq org-read-date-overlay nil)))))))
 
      (t ; Naked prompt only
@@ -12566,10 +14306,14 @@ user."
          (setq ans (read-string prompt default-input
                                 'org-read-date-history timestr))
        (when org-read-date-overlay
-         (org-delete-overlay org-read-date-overlay)
+         (delete-overlay org-read-date-overlay)
          (setq org-read-date-overlay nil)))))
 
     (setq final (org-read-date-analyze ans def defdecode))
+
+    ;; One round trip to get rid of 34th of August and stuff like that....
+    (setq final (decode-time (apply 'encode-time final)))
+
     (setq org-read-date-final-answer ans)
 
     (if to-time
@@ -12583,11 +14327,12 @@ user."
 (defvar def)
 (defvar defdecode)
 (defvar with-time)
+(defvar org-read-date-analyze-futurep nil)
 (defun org-read-date-display ()
   "Display the current date prompt interpretation in the minibuffer."
   (when org-read-date-display-live
     (when org-read-date-overlay
-      (org-delete-overlay org-read-date-overlay))
+      (delete-overlay org-read-date-overlay))
     (let ((p (point)))
       (end-of-line 1)
       (while (not (equal (buffer-substring
@@ -12612,17 +14357,20 @@ user."
        (setq txt (concat (substring txt 0 (match-end 0)) "-"
                          org-end-time-was-given
                          (substring txt (match-end 0)))))
+      (when org-read-date-analyze-futurep
+       (setq txt (concat txt " (=>F)")))
       (setq org-read-date-overlay
-           (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
+           (make-overlay (1- (point-at-eol)) (point-at-eol)))
       (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
 
 (defun org-read-date-analyze (ans def defdecode)
-  "Analyse the combined answer of the date prompt."
+  "Analyze the combined answer of the date prompt."
   ;; FIXME: cleanup and comment
-  (let (delta deltan deltaw deltadef year month day
-             hour minute second wday pm h2 m2 tl wday1
-             iso-year iso-weekday iso-week iso-year iso-date)
-
+  (let ((nowdecode (decode-time (current-time)))
+       delta deltan deltaw deltadef year month day
+       hour minute second wday pm h2 m2 tl wday1
+       iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
+    (setq org-read-date-analyze-futurep nil)
     (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
       (setq ans "+0"))
 
@@ -12633,25 +14381,41 @@ user."
             deltadef (nth 2 delta)))
 
     ;; Check if there is an iso week date in there
-    ;; If yes, sore the info and postpone interpreting it until the rest
+    ;; If yes, store the info and postpone interpreting it until the rest
     ;; of the parsing is done
     (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
-      (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
-           iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
+      (setq iso-year (if (match-end 1)
+                        (org-small-year-to-year
+                         (string-to-number (match-string 1 ans))))
+           iso-weekday (if (match-end 3)
+                           (string-to-number (match-string 3 ans)))
            iso-week (string-to-number (match-string 2 ans)))
       (setq ans (replace-match "" t t ans)))
 
-    ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
+    ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
     (when (string-match
           "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
       (setq year (if (match-end 2)
                     (string-to-number (match-string 2 ans))
-                  (string-to-number (format-time-string "%Y")))
+                  (progn (setq kill-year t)
+                         (string-to-number (format-time-string "%Y"))))
            month (string-to-number (match-string 3 ans))
            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)))
+    ;; Help matching american dates, like 5/30 or 5/30/7
+    (when (string-match
+          "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
+      (setq year (if (match-end 4)
+                    (string-to-number (match-string 4 ans))
+                  (progn (setq kill-year t)
+                         (string-to-number (format-time-string "%Y"))))
+           month (string-to-number (match-string 1 ans))
+           day (string-to-number (match-string 2 ans)))
+      (if (< year 100) (setq year (+ 2000 year)))
+      (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
+                              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
     ;; so that matching will be successful.
@@ -12694,23 +14458,38 @@ user."
          day (or (nth 3 tl) (nth 3 defdecode))
          month (or (nth 4 tl)
                    (if (and org-read-date-prefer-future
-                            (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
-                       (1+ (nth 4 defdecode))
+                            (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
+                       (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
                      (nth 4 defdecode)))
-         year (or (nth 5 tl)
+         year (or (and (not kill-year) (nth 5 tl))
                   (if (and org-read-date-prefer-future
-                           (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
-                      (1+ (nth 5 defdecode))
+                           (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
+                      (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
                     (nth 5 defdecode)))
          hour (or (nth 2 tl) (nth 2 defdecode))
          minute (or (nth 1 tl) (nth 1 defdecode))
          second (or (nth 0 tl) 0)
          wday (nth 6 tl))
 
+    (when (and (eq org-read-date-prefer-future 'time)
+              (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
+              (equal day (nth 3 nowdecode))
+              (equal month (nth 4 nowdecode))
+              (equal year (nth 5 nowdecode))
+              (nth 2 tl)
+              (or (< (nth 2 tl) (nth 2 nowdecode))
+                  (and (= (nth 2 tl) (nth 2 nowdecode))
+                       (nth 1 tl)
+                       (< (nth 1 tl) (nth 1 nowdecode)))))
+      (setq day (1+ day)
+           futurep t))
+
     ;; Special date definitions below
     (cond
      (iso-week
       ;; There was an iso week
+      (require 'cal-iso)
+      (setq futurep nil)
       (setq year (or iso-year year)
            day (or iso-weekday wday 1)
            wday nil ; to make sure that the trigger below does not match
@@ -12730,6 +14509,7 @@ user."
            year (nth 2 iso-date)
            day (nth 1 iso-date)))
      (deltan
+      (setq futurep nil)
       (unless deltadef
        (let ((now (decode-time (current-time))))
          (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
@@ -12738,6 +14518,7 @@ user."
            ((equal deltaw "m") (setq month (+ month deltan)))
            ((equal deltaw "y") (setq year (+ year deltan)))))
      ((and wday (not (nth 3 tl)))
+      (setq futurep nil)
       ;; Weekday was given, but no day, so pick that day in the week
       ;; on or after the derived date.
       (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
@@ -12748,6 +14529,7 @@ user."
        (setq org-time-was-given t))
     (if (< year 100) (setq year (+ 2000 year)))
     (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
+    (setq org-read-date-analyze-futurep futurep)
     (list second minute hour day month year)))
 
 (defvar parse-time-weekdays)
@@ -12786,6 +14568,24 @@ DEF-FLAG   is t when a double ++ or -- indicates shift relative to
            (list delta "d" rel))
        (list (* n (if (= dir ?-) -1 1)) what rel)))))
 
+(defun org-order-calendar-date-args (arg1 arg2 arg3)
+  "Turn a user-specified date into the internal representation.
+The internal representation needed by the calendar is (month day year).
+This is a wrapper to handle the brain-dead convention in calendar that
+user function argument order change dependent on argument order."
+  (if (boundp 'calendar-date-style)
+      (cond
+       ((eq calendar-date-style 'american)
+       (list arg1 arg2 arg3))
+       ((eq calendar-date-style 'european)
+       (list arg2 arg1 arg3))
+       ((eq calendar-date-style 'iso)
+       (list arg2 arg3 arg1)))
+    (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
+      (if (org-bound-and-true-p european-calendar-style)
+         (list arg2 arg1 arg3)
+       (list arg1 arg2 arg3)))))
+
 (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."
@@ -12797,7 +14597,7 @@ Also, store the cursor date in variable org-ans2."
       (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))
+    (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
     (select-window sw)
     (org-select-frame-set-input-focus sf)))
 
@@ -12813,7 +14613,7 @@ This is used by `org-read-date' in a temporary keymap for the calendar buffer."
 
 (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.
+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
 stamp will not contribute to the agenda.
 PRE and POST are optional strings to be inserted before and after the
@@ -12823,7 +14623,6 @@ The command returns the inserted time stamp."
        stamp)
     (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
     (insert-before-markers (or pre ""))
-    (insert-before-markers (setq stamp (format-time-string fmt time)))
     (when (listp extra)
       (setq extra (car extra))
       (if (and (stringp extra)
@@ -12833,9 +14632,8 @@ The command returns the inserted time stamp."
                              (string-to-number (match-string 2 extra))))
        (setq extra nil)))
     (when extra
-      (backward-char 1)
-      (insert-before-markers extra)
-      (forward-char 1))
+      (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
+    (insert-before-markers (setq stamp (format-time-string fmt time)))
     (insert-before-markers (or post ""))
     (setq org-last-inserted-timestamp stamp)))
 
@@ -12866,7 +14664,7 @@ The command returns the inserted time stamp."
         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]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
+      (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
          (setq off (- (match-end 0) (match-beginning 0)))))
     (setq end (- end off))
     (setq w1 (- end beg)
@@ -13091,7 +14889,7 @@ days in order to avoid rounding problems."
 
 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
   "Convert a time stamp to an absolute day number.
-If there is a specifyer for a cyclic time stamp, get the closest date to
+If there is a specifier for a cyclic time stamp, get the closest date to
 DAYNR.
 PREFER and SHOW-ALL are passed through to `org-closest-date'.
 the variable date is bound by the calendar when this is called."
@@ -13150,9 +14948,12 @@ D may be an absolute day number, or a calendar-type list (month day year)."
                              (org-current-line)
                              (buffer-file-name) sexp)
                      (sleep-for 2))))))
-    (cond ((stringp result) result)
+    (cond ((stringp result) (split-string result "; "))
          ((and (consp result)
+               (not (consp (cdr result)))
                (stringp (cdr result))) (cdr result))
+         ((and (consp result)
+               (stringp (car result))) result)
          (result entry)
           (t nil))))
 
@@ -13165,8 +14966,7 @@ This uses the icalendar.el library."
         (tmpfile (make-temp-name
                   (expand-file-name "orgics" tmpdir)))
         buf rtn b e)
-    (save-excursion
-      (set-buffer frombuf)
+    (with-current-buffer frombuf
       (icalendar-export-region (point-min) (point-max) tmpfile)
       (setq buf (find-buffer-visiting tmpfile))
       (set-buffer buf)
@@ -13205,7 +15005,7 @@ When SHOW-ALL is nil, only return the current occurrence of a time stamp."
       (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))
+       (error "Invalid change specifier: %s" change))
       (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
       (cond
        ((eq dw 'day)
@@ -13242,16 +15042,16 @@ When SHOW-ALL is nil, only return the current occurrence of a time stamp."
       (setq n0 n1  n1 (min n1 n2)  n2 (max n0 n2))
       (if show-all
          (cond
-          ((eq prefer 'past) n1)
+          ((eq prefer 'past)   (if (= cday n2) n2 n1))
           ((eq prefer 'future) (if (= cday n1) n1 n2))
           (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
        (cond
-        ((eq prefer 'past) n1)
+        ((eq prefer 'past)   (if (= cday n2) n2 n1))
         ((eq prefer 'future) (if (= cday n1) n1 n2))
         (t (if (= cday n1) n1 n2)))))))
 
 (defun org-date-to-gregorian (date)
-  "Turn any specification of DATE into a gregorian date for the calendar."
+  "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)
@@ -13283,7 +15083,7 @@ If the cursor is on the year, change the year.  If it is on the month or
 the day, change that.
 With prefix ARG, change by that many units."
   (interactive "p")
-  (org-timestamp-change (prefix-numeric-value arg)))
+  (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
 
 (defun org-timestamp-down (&optional arg)
   "Decrease the date item at the cursor by one.
@@ -13291,7 +15091,7 @@ If the cursor is on the year, change the year.  If it is on the month or
 the day, change that.
 With prefix ARG, change by that many units."
   (interactive "p")
-  (org-timestamp-change (- (prefix-numeric-value arg))))
+  (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
 
 (defun org-timestamp-up-day (&optional arg)
   "Increase the date in the time stamp by one day.
@@ -13300,7 +15100,7 @@ With prefix ARG, change that many days."
   (if (and (not (org-at-timestamp-p t))
           (org-on-heading-p))
       (org-todo 'up)
-    (org-timestamp-change (prefix-numeric-value arg) 'day)))
+    (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
 
 (defun org-timestamp-down-day (&optional arg)
   "Decrease the date in the time stamp by one day.
@@ -13309,7 +15109,7 @@ With prefix ARG, change that many days."
   (if (and (not (org-at-timestamp-p t))
           (org-on-heading-p))
       (org-todo 'down)
-    (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
+    (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
 
 (defun org-at-timestamp-p (&optional inactive-ok)
   "Determine if the cursor is in or at a timestamp."
@@ -13354,7 +15154,7 @@ With prefix ARG, change that many days."
       (message "Timestamp is now %sactive"
               (if (equal (char-after beg) ?<) "" "in")))))
 
-(defun org-timestamp-change (n &optional what)
+(defun org-timestamp-change (n &optional what updown)
   "Change the date in the time stamp at point.
 The date will be changed by N times WHAT.  WHAT can be `day', `month',
 `year', `minute', `second'.  If WHAT is not given, the cursor position
@@ -13379,14 +15179,16 @@ in the timestamp determines what will be changed."
            ts (match-string 0))
       (replace-match "")
       (if (string-match
-          "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
+          "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
           ts)
          (setq extra (match-string 1 ts)))
       (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
          (setq with-hm t))
       (setq time0 (org-parse-time-string ts))
-      (when (and (eq org-ts-what 'minute)
-                (eq current-prefix-arg nil))
+      (when (and updown
+                (eq org-ts-what 'minute)
+                (not current-prefix-arg))
+       ;; This looks like s-up and s-down.  Change by one rounding step.
        (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
        (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
          (setcar (cdr time0) (+ (nth 1 time0)
@@ -13483,9 +15285,7 @@ A prefix ARG can be used to force the current date."
   (let ((tsr org-ts-regexp) diff
        (calendar-move-hook nil)
        (calendar-view-holidays-initially-flag nil)
-       (view-calendar-holidays-initially nil)
-       (calendar-view-diary-initially-flag nil)
-       (view-diary-entries-initially nil))
+       (calendar-view-diary-initially-flag nil))
     (if (or (org-at-timestamp-p)
            (save-excursion
              (beginning-of-line 1)
@@ -13522,7 +15322,7 @@ If there is already a time stamp at the cursor position, update it."
 
 (defun org-hh:mm-string-to-minutes (s)
   "Convert a string H:MM to a number of minutes.
-If the string is just a number, interprete it as minutes.
+If the string is just a number, interpret it as minutes.
 In fact, the first hh:mm or number in the string will be taken,
 there can be extra stuff in the string.
 If no number is found, the return value is 0."
@@ -13575,21 +15375,31 @@ changes from another.  I believe the procedure must be like this:
 ;;;; Agenda files
 
 ;;;###autoload
-(defun org-iswitchb (&optional arg)
-  "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
+(defun org-switchb (&optional arg)
+  "Switch between Org buffers.
 With a prefix argument, restrict available to files.
-With two prefix arguments, restrict available buffers to agenda files."
+With two prefix arguments, restrict available buffers to agenda files.
+
+Defaults to `iswitchb' for buffer name completion.
+Set `org-completion-use-ido' to make it use ido instead."
   (interactive "P")
   (let ((blist (cond ((equal arg '(4))  (org-buffer-list 'files))
                      ((equal arg '(16)) (org-buffer-list 'agenda))
-                     (t                 (org-buffer-list)))))
+                     (t                 (org-buffer-list))))
+       (org-completion-use-iswitchb org-completion-use-iswitchb)
+       (org-completion-use-ido org-completion-use-ido))
+    (unless (or org-completion-use-ido org-completion-use-iswitchb)
+      (setq org-completion-use-iswitchb t))
     (switch-to-buffer
      (org-icompleting-read "Org buffer: "
-                              (mapcar 'list (mapcar 'buffer-name blist))
-                              nil t))))
+                          (mapcar 'list (mapcar 'buffer-name blist))
+                          nil t))))
 
+;;; Define some older names previously used for this functionality
+;;;###autoload
+(defalias 'org-ido-switchb 'org-switchb)
 ;;;###autoload
-(defalias 'org-ido-switchb 'org-iswitchb)
+(defalias 'org-iswitchb 'org-switchb)
 
 (defun org-buffer-list (&optional predicate exclude-tmp)
   "Return a list of Org buffers.
@@ -13633,7 +15443,7 @@ If EXCLUDE-TMP is non-nil, ignore temporary buffers."
   "Get the list of agenda files.
 Optional UNRESTRICTED means return the full list even if a restriction
 is currently in place.
-When ARCHIVES is t, include all archive files hat are really being
+When ARCHIVES is t, include all archive files that are really being
 used by the agenda files.  If ARCHIVE is `ifmode', do this only if
 `org-agenda-archives-mode' is t."
   (let ((files
@@ -13660,6 +15470,13 @@ used by the agenda files.  If ARCHIVE is `ifmode', do this only if
       (setq files (org-add-archive-files files)))
     files))
 
+(defun org-agenda-file-p (&optional file)
+  "Return non-nil, if FILE is an agenda file.
+If FILE is omitted, use the file associated with the current
+buffer."
+  (member (or file (buffer-file-name))
+          (org-agenda-files t)))
+
 (defun org-edit-agenda-file-list ()
   "Edit the list of agenda files.
 Depending on setup, this either uses customize to edit the variable
@@ -13686,24 +15503,41 @@ the buffer and restores the previous window configuration."
 (defun org-store-new-agenda-file-list (list)
   "Set new value for the agenda file list and save it correctly."
   (if (stringp org-agenda-files)
-      (let ((f org-agenda-files) b)
-       (while (setq b (find-buffer-visiting f)) (kill-buffer b))
-       (with-temp-file f
-         (insert (mapconcat 'identity list "\n") "\n")))
+      (let ((fe (org-read-agenda-file-list t)) b u)
+       (while (setq b (find-buffer-visiting org-agenda-files))
+         (kill-buffer b))
+       (with-temp-file org-agenda-files
+         (insert
+          (mapconcat
+           (lambda (f) ;; Keep un-expanded entries.
+             (if (setq u (assoc f fe))
+                 (cdr u)
+               f))
+           list "\n")
+          "\n")))
     (let ((org-mode-hook nil) (org-inhibit-startup t)
          (org-insert-mode-line-in-empty-file nil))
       (setq org-agenda-files list)
       (customize-save-variable 'org-agenda-files org-agenda-files))))
 
-(defun org-read-agenda-file-list ()
-  "Read the list of agenda files from a file."
+(defun org-read-agenda-file-list (&optional pair-with-expansion)
+  "Read the list of agenda files from a file.
+If PAIR-WITH-EXPANSION is t return pairs with un-expanded
+filenames, used by `org-store-new-agenda-file-list' to write back
+un-expanded file names."
   (when (file-directory-p org-agenda-files)
     (error "`org-agenda-files' cannot be a single directory"))
   (when (stringp org-agenda-files)
     (with-temp-buffer
       (insert-file-contents org-agenda-files)
-      (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
-
+      (mapcar
+       (lambda (f)
+        (let ((e (expand-file-name (substitute-in-file-name f)
+                                   org-directory)))
+          (if pair-with-expansion
+              (cons e f)
+            e)))
+       (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
 
 ;;;###autoload
 (defun org-cycle-agenda-files ()
@@ -13751,7 +15585,7 @@ end of the list."
 (defun org-remove-file (&optional file)
   "Remove current file from the list of files in variable `org-agenda-files'.
 These are the files which are being checked for agenda entries.
-Optional argument FILE means, use this file instead of the current."
+Optional argument FILE means use this file instead of the current."
   (interactive)
   (let* ((org-agenda-skip-unavailable-files nil)
         (file (or file buffer-file-name))
@@ -13776,7 +15610,7 @@ Optional argument FILE means, use this file instead of the current."
 (defun org-check-agenda-file (file)
   "Make sure FILE exists.  If not, ask user what to do."
   (when (not (file-exists-p file))
-    (message "non-existent file %s. [R]emove from list or [A]bort?"
+    (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
             (abbreviate-file-name file))
     (let ((r (downcase (read-char-exclusive))))
       (cond
@@ -13835,6 +15669,8 @@ When a buffer is unmodified, it is just killed.  When modified, it is saved
                  (append org-done-keywords-for-agenda org-done-keywords))
            (setq org-todo-keyword-alist-for-agenda
                  (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
+           (setq org-drawers-for-agenda
+                 (append org-drawers-for-agenda org-drawers))
            (setq org-tag-alist-for-agenda
                  (append org-tag-alist-for-agenda org-tag-alist))
 
@@ -13851,6 +15687,8 @@ When a buffer is unmodified, it is just killed.  When modified, it is saved
                (add-text-properties
                 (match-beginning 0) (org-end-of-subtree t) pc)))
            (set-buffer-modified-p bmp)))))
+    (setq org-todo-keywords-for-agenda
+          (org-uniquify org-todo-keywords-for-agenda))
     (setq org-todo-keyword-alist-for-agenda
          (org-uniquify org-todo-keyword-alist-for-agenda)
          org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
@@ -13946,6 +15784,11 @@ looks only before point, not after."
        (goto-char pos)
        (if dd-on (cons "$$" m))))))
 
+(defun org-inside-latex-macro-p ()
+  "Is point inside a LaTeX macro or its arguments?"
+  (save-match-data
+    (org-in-regexp
+     "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
 
 (defun org-try-cdlatex-tab ()
   "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
@@ -13988,7 +15831,7 @@ Revert to the normal definition outside of these fragments."
 
 (defun org-remove-latex-fragment-image-overlays ()
   "Remove all overlays with LaTeX fragment images in current buffer."
-  (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
+  (mapc 'delete-overlay org-latex-fragment-image-overlays)
   (setq org-latex-fragment-image-overlays nil))
 
 (defun org-preview-latex-fragment (&optional subtree)
@@ -13997,7 +15840,8 @@ If the cursor is in a LaTeX fragment, create the image and overlay
 it over the source code.  If there is no fragment at point, display
 all fragments in the current text, from one headline to the next.  With
 prefix SUBTREE, display all fragments in the current subtree.  With a
-double prefix `C-u C-u', or when the cursor is before the first headline,
+double prefix arg \\[universal-argument] \\[universal-argument], or when \
+the cursor is before the first headline,
 display all fragments in the buffer.
 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
   (interactive "P")
@@ -14029,7 +15873,7 @@ The images can be removed again with \\[org-ctrl-c-ctrl-c]."
         (concat "ltxpng/" (file-name-sans-extension
                            (file-name-nondirectory
                             buffer-file-name)))
-        default-directory 'overlays msg at 'forbuffer)
+        default-directory 'overlays msg at 'forbuffer 'dvipng)
       (message msg "done.  Use `C-c C-c' to remove images.")))))
 
 (defvar org-latex-regexps
@@ -14043,8 +15887,12 @@ The images can be removed again with \\[org-ctrl-c-ctrl-c]."
     ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
   "Regular expressions for matching embedded LaTeX.")
 
-(defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
-  "Replace LaTeX fragments with links to an image, and produce images."
+(defvar org-export-have-math nil) ;; dynamic scoping
+(defun org-format-latex (prefix &optional dir overlays msg at
+                               forbuffer processing-type)
+  "Replace LaTeX fragments with links to an image, and produce images.
+Some of the options can be changed using the variable
+`org-format-latex-options'."
   (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
   (let* ((prefixnodir (file-name-nondirectory prefix))
         (absprefix (expand-file-name prefix dir))
@@ -14052,15 +15900,11 @@ The images can be removed again with \\[org-ctrl-c-ctrl-c]."
         (opt org-format-latex-options)
         (matchers (plist-get opt :matchers))
         (re-list org-latex-regexps)
-        (cnt 0) txt link beg end re e checkdir
-        executables-checked
+        (org-format-latex-header-extra
+         (plist-get (org-infile-export-plist) :latex-header-extra))
+        (cnt 0) txt hash link beg end re e checkdir
+        executables-checked string
         m n block linkfile movefile ov)
-    ;; Check if there are old images files with this prefix, and remove them
-    (when (file-directory-p todir)
-      (mapc 'delete-file
-           (directory-files
-            todir 'full
-            (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
     ;; Check the different regular expressions
     (while (setq e (pop re-list))
       (setq m (car e) re (nth 1 e) n (nth 2 e)
@@ -14075,53 +15919,85 @@ The images can be removed again with \\[org-ctrl-c-ctrl-c]."
                         (not (eq (get-char-property (match-beginning n)
                                                     'org-overlay-type)
                                  'org-latex-overlay))))
-           (setq txt (match-string n)
-                 beg (match-beginning n) end (match-end n)
-                 cnt (1+ cnt)
-                 linkfile (format "%s_%04d.png" prefix cnt)
-                 movefile (format "%s_%04d.png" absprefix cnt)
-                 link (concat block "[[file:" linkfile "]]" block))
-           (if msg (message msg cnt))
-           (goto-char beg)
-           (unless checkdir ; make sure the directory exists
-             (setq checkdir t)
-             (or (file-directory-p todir) (make-directory todir)))
-
-           (unless executables-checked
-             (org-check-external-command
-              "latex" "needed to convert LaTeX fragments to images")
-             (org-check-external-command
-              "dvipng" "needed to convert LaTeX fragments to images")
-             (setq executables-checked t))
-
-           (org-create-formula-image
-            txt movefile opt forbuffer)
-           (if overlays
-               (progn
-                 (mapc (lambda (o)
-                         (if (eq (org-overlay-get o 'org-overlay-type)
-                                 'org-latex-overlay)
-                             (org-delete-overlay o)))
-                       (org-overlays-in beg end))
-                 (setq ov (org-make-overlay beg end))
-                 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
-                 (if (featurep 'xemacs)
-                     (progn
-                       (org-overlay-put ov 'invisible t)
-                       (org-overlay-put
-                        ov 'end-glyph
-                        (make-glyph (vector 'png :file movefile))))
-                   (org-overlay-put
-                    ov 'display
-                    (list 'image :type 'png :file movefile :ascent 'center)))
-                 (push ov org-latex-fragment-image-overlays)
-                 (goto-char end))
-             (delete-region beg end)
-             (insert link))))))))
-
-(defvar org-export-latex-packages-alist) ;; defined in org-latex.el
+           (setq org-export-have-math t)
+           (cond
+            ((eq processing-type 'verbatim)
+             ;; Leave the text verbatim, just protect it
+             (add-text-properties (match-beginning n) (match-end n)
+                                  '(org-protected t)))
+            ((eq processing-type 'mathjax)
+             ;; Prepare for MathJax processing
+             (setq string (match-string n))
+             (if (member m '("$" "$1"))
+                 (save-excursion
+                   (delete-region (match-beginning n) (match-end n))
+                   (goto-char (match-beginning n))
+                   (insert (org-add-props (concat "\\(" (substring string 1 -1)
+                                                  "\\)")
+                               '(org-protected t))))
+               (add-text-properties (match-beginning n) (match-end n)
+                                    '(org-protected t))))
+            ((or (eq processing-type 'dvipng) t)
+             ;; Process to an image
+             (setq txt (match-string n)
+                   beg (match-beginning n) end (match-end n)
+                   cnt (1+ cnt))
+             (let (print-length print-level) ; make sure full list is printed
+               (setq hash (sha1 (prin1-to-string
+                                 (list org-format-latex-header
+                                       org-format-latex-header-extra
+                                       org-export-latex-default-packages-alist
+                                       org-export-latex-packages-alist
+                                       org-format-latex-options
+                                       forbuffer txt)))
+                     linkfile (format "%s_%s.png" prefix hash)
+                     movefile (format "%s_%s.png" absprefix hash)))
+             (setq link (concat block "[[file:" linkfile "]]" block))
+             (if msg (message msg cnt))
+             (goto-char beg)
+             (unless checkdir ; make sure the directory exists
+               (setq checkdir t)
+               (or (file-directory-p todir) (make-directory todir t)))
+
+             (unless executables-checked
+               (org-check-external-command
+                "latex" "needed to convert LaTeX fragments to images")
+               (org-check-external-command
+                "dvipng" "needed to convert LaTeX fragments to images")
+               (setq executables-checked t))
+
+             (unless (file-exists-p movefile)
+               (org-create-formula-image
+                txt movefile opt forbuffer))
+             (if overlays
+                 (progn
+                   (mapc (lambda (o)
+                           (if (eq (overlay-get o 'org-overlay-type)
+                                   'org-latex-overlay)
+                               (delete-overlay o)))
+                         (overlays-in beg end))
+                   (setq ov (make-overlay beg end))
+                   (overlay-put ov 'org-overlay-type 'org-latex-overlay)
+                   (if (featurep 'xemacs)
+                       (progn
+                         (overlay-put ov 'invisible t)
+                         (overlay-put
+                          ov 'end-glyph
+                          (make-glyph (vector 'png :file movefile))))
+                     (overlay-put
+                      ov 'display
+                      (list 'image :type 'png :file movefile :ascent 'center)))
+                   (push ov org-latex-fragment-image-overlays)
+                   (goto-char end))
+               (delete-region beg end)
+               (insert (org-add-props link
+                           (list 'org-latex-src
+                                 (replace-regexp-in-string
+                                  "\"" "" txt)))))))))))))
+
 ;; This function borrows from Ganesh Swami's latex2png.el
 (defun org-create-formula-image (string tofile options buffer)
+  "This calls dvipng."
   (require 'org-latex)
   (let* ((tmpdir (if (featurep 'xemacs)
                     (temp-directory)
@@ -14143,17 +16019,14 @@ The images can be removed again with \\[org-ctrl-c-ctrl-c]."
     (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 org-format-latex-header
-             (if org-export-latex-packages-alist
-                 (concat "\n"
-                         (mapconcat (lambda(p)
-                                      (if (equal "" (car p))
-                                          (format "\\usepackage{%s}" (cadr p))
-                                        (format "\\usepackage[%s]{%s}"
-                                                (car p) (cadr p))))
-                                    org-export-latex-packages-alist "\n"))
-               "")
-             "\n\\begin{document}\n" string "\n\\end{document}\n"))
+      (insert (org-splice-latex-header
+              org-format-latex-header
+              org-export-latex-default-packages-alist
+              org-export-latex-packages-alist t
+              org-format-latex-header-extra))
+      (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
+      (require 'org-latex)
+      (org-export-latex-fix-inputenc))
     (let ((dir default-directory))
       (condition-case nil
          (progn
@@ -14173,13 +16046,75 @@ The images can be removed again with \\[org-ctrl-c-ctrl-c]."
                        dvifile)
        (error nil))
       (if (not (file-exists-p pngfile))
-         (progn (message "Failed to create png file from %s" texfile) nil)
+         (if org-format-latex-signal-error
+             (error "Failed to create png file from %s" texfile)
+           (message "Failed to create png file from %s" texfile)
+           nil)
        ;; Use the requested file name and clean up
        (copy-file pngfile tofile 'replace)
        (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
              (delete-file (concat texfilebase e)))
        pngfile))))
 
+(defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
+  "Fill a LaTeX header template TPL.
+In the template, the following place holders will be recognized:
+
+ [DEFAULT-PACKAGES]      \\usepackage statements for DEF-PKG
+ [NO-DEFAULT-PACKAGES]   do not include DEF-PKG
+ [PACKAGES]              \\usepackage statements for PKG
+ [NO-PACKAGES]           do not include PKG
+ [EXTRA]                 the string EXTRA
+ [NO-EXTRA]              do not include EXTRA
+
+For backward compatibility, if both the positive and the negative place
+holder is missing, the positive one (without the \"NO-\") will be
+assumed to be present at the end of the template.
+DEF-PKG and PKG are assumed to be alists of options/packagename lists.
+EXTRA is a string.
+SNIPPETS-P indicates if this is run to create snippet images for HTML."
+  (let (rpl (end ""))
+    (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
+       (setq rpl (if (or (match-end 1) (not def-pkg))
+                     "" (org-latex-packages-to-string def-pkg snippets-p t))
+             tpl (replace-match rpl t t tpl))
+      (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
+
+    (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
+       (setq rpl (if (or (match-end 1) (not pkg))
+                     "" (org-latex-packages-to-string pkg snippets-p t))
+             tpl (replace-match rpl t t tpl))
+      (if pkg (setq end
+                   (concat end "\n"
+                           (org-latex-packages-to-string pkg snippets-p)))))
+
+    (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
+       (setq rpl (if (or (match-end 1) (not extra))
+                     "" (concat extra "\n"))
+             tpl (replace-match rpl t t tpl))
+      (if (and extra (string-match "\\S-" extra))
+         (setq end (concat end "\n" extra))))
+
+    (if (string-match "\\S-" end)
+       (concat tpl "\n" end)
+      tpl)))
+
+(defun org-latex-packages-to-string (pkg &optional snippets-p newline)
+  "Turn an alist of packages into a string with the \\usepackage macros."
+  (setq pkg (mapconcat (lambda(p)
+                        (cond
+                         ((stringp p) p)
+                         ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
+                          (format "%% Package %s omitted" (cadr p)))
+                         ((equal "" (car p))
+                          (format "\\usepackage{%s}" (cadr p)))
+                         (t
+                          (format "\\usepackage[%s]{%s}"
+                                  (car p) (cadr p)))))
+                      pkg
+                      "\n"))
+  (if newline (concat pkg "\n") pkg))
+
 (defun org-dvipng-color (attr)
   "Return an rgb color specification for dvipng."
   (apply 'format "rgb %s %s %s"
@@ -14190,6 +16125,80 @@ The images can be removed again with \\[org-ctrl-c-ctrl-c]."
   "Return string to be used as color value for an RGB component."
   (format "%g" (/ value 65535.0)))
 
+;; Image display
+
+
+(defvar org-inline-image-overlays nil)
+(make-variable-buffer-local 'org-inline-image-overlays)
+
+(defun org-toggle-inline-images (&optional include-linked)
+  "Toggle the display of inline images.
+INCLUDE-LINKED is passed to `org-display-inline-images'."
+  (interactive "P")
+  (if org-inline-image-overlays
+      (progn
+       (org-remove-inline-images)
+       (message "Inline image display turned off"))
+    (org-display-inline-images include-linked)
+    (if org-inline-image-overlays
+       (message "%d images displayed inline"
+                (length org-inline-image-overlays))
+      (message "No images to display inline"))))
+
+(defun org-display-inline-images (&optional include-linked refresh beg end)
+  "Display inline images.
+Normally only links without a description part are inlined, because this
+is how it will work for export.  When INCLUDE-LINKED is set, also links
+with a description part will be inlined.  This can be nice for a quick
+look at those images, but it does not reflect what exported files will look
+like.
+When REFRESH is set, refresh existing images between BEG and END.
+This will create new image displays only if necessary.
+BEG and END default to the buffer boundaries."
+  (interactive "P")
+  (unless refresh
+    (org-remove-inline-images)
+    (clear-image-cache))
+  (save-excursion
+    (save-restriction
+      (widen)
+      (setq beg (or beg (point-min)) end (or end (point-max)))
+      (goto-char (point-min))
+      (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
+                       (substring (org-image-file-name-regexp) 0 -2)
+                       "\\)\\]" (if include-linked "" "\\]")))
+           old file ov img)
+       (while (re-search-forward re end t)
+         (setq old (get-char-property-and-overlay (match-beginning 1)
+                                                  'org-image-overlay))
+         (setq file (expand-file-name
+                     (concat (or (match-string 3) "") (match-string 4))))
+         (when (file-exists-p file)
+           (if (and (car-safe old) refresh)
+               (image-refresh (overlay-get (cdr old) 'display))
+             (setq img (save-match-data (create-image file)))
+             (when img
+               (setq ov (make-overlay (match-beginning 0) (match-end 0)))
+               (overlay-put ov 'display img)
+               (overlay-put ov 'face 'default)
+               (overlay-put ov 'org-image-overlay t)
+               (overlay-put ov 'modification-hooks
+                            (list 'org-display-inline-modification-hook))
+               (push ov org-inline-image-overlays)))))))))
+
+(defun org-display-inline-modification-hook (ov after beg end &optional len)
+  "Remove inline-display overlay if a corresponding region is modified."
+  (let ((inhibit-modification-hooks t))
+    (when (and ov after)
+      (delete ov org-inline-image-overlays)
+      (delete-overlay ov))))
+
+(defun org-remove-inline-images ()
+  "Remove inline display of images."
+  (interactive)
+  (mapc 'delete-overlay org-inline-image-overlays)
+  (setq org-inline-image-overlays nil))
+
 ;;;; Key bindings
 
 ;; Make `C-c C-x' a prefix key
@@ -14199,9 +16208,9 @@ The images can be removed again with \\[org-ctrl-c-ctrl-c]."
 (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)
+(org-defkey org-mode-map [(meta tab)] 'pcomplete)
+(org-defkey org-mode-map "\M-\t" 'pcomplete)
+(org-defkey org-mode-map "\M-\C-i"      'pcomplete)
 ;; The following line is necessary under Suse GNU/Linux
 (unless (featurep 'xemacs)
   (org-defkey org-mode-map [S-iso-lefttab]  'org-shifttab))
@@ -14231,6 +16240,12 @@ The images can be removed again with \\[org-ctrl-c-ctrl-c]."
 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
 (org-defkey org-mode-map [(control shift left)]  'org-shiftcontrolleft)
 
+;; Babel keys
+(define-key org-mode-map org-babel-key-prefix org-babel-map)
+(mapc (lambda (pair)
+        (define-key org-babel-map (car pair) (cdr pair)))
+      org-babel-key-bindings)
+
 ;;; Extra keys for tty access.
 ;;  We only set them when really needed because otherwise the
 ;;  menus don't show the simple keys
@@ -14260,7 +16275,7 @@ The images can be removed again with \\[org-ctrl-c-ctrl-c]."
   (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)
-  (org-defkey org-mode-map [?\e (tab)] 'org-complete)
+  (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
   (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
   (org-defkey org-mode-map [?\e (shift left)]   'org-shiftmetaleft)
   (org-defkey org-mode-map [?\e (shift right)]  'org-shiftmetaright)
@@ -14278,7 +16293,7 @@ The images can be removed again with \\[org-ctrl-c-ctrl-c]."
 (org-defkey org-mode-map "\C-c\C-b"    'org-backward-same-level)
 (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-x\C-a" 'org-archive-subtree-default)
 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
@@ -14288,7 +16303,6 @@ The images can be removed again with \\[org-ctrl-c-ctrl-c]."
 (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-refile)
 (org-defkey org-mode-map "\C-c/"    'org-sparse-tree)   ; Minor-mode reserved
 (org-defkey org-mode-map "\C-c\\"   'org-match-sparse-tree) ; Minor-mode res.
@@ -14340,6 +16354,9 @@ The images can be removed again with \\[org-ctrl-c-ctrl-c]."
 (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-xf"    'org-footnote-action)
+(org-defkey org-mode-map "\C-c\C-x\C-mg"    'org-mobile-pull)
+(org-defkey org-mode-map "\C-c\C-x\C-mp"    'org-mobile-push)
+(org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
 
@@ -14357,16 +16374,20 @@ The images can be removed again with \\[org-ctrl-c-ctrl-c]."
 (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-v" 'org-toggle-inline-images)
+(org-defkey org-mode-map "\C-c\C-x\\"   'org-toggle-pretty-entities)
 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
 (org-defkey org-mode-map "\C-c\C-xp"    'org-set-property)
 (org-defkey org-mode-map "\C-c\C-xe"    'org-set-effort)
 (org-defkey org-mode-map "\C-c\C-xo"    'org-toggle-ordered-property)
 (org-defkey org-mode-map "\C-c\C-xi"    'org-insert-columns-dblock)
 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
+(org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
 
 (org-defkey org-mode-map "\C-c\C-x."    'org-timer)
 (org-defkey org-mode-map "\C-c\C-x-"    'org-timer-item)
 (org-defkey org-mode-map "\C-c\C-x0"    'org-timer-start)
+(org-defkey org-mode-map "\C-c\C-x_"    'org-timer-stop)
 (org-defkey org-mode-map "\C-c\C-x,"    'org-timer-pause-or-continue)
 
 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
@@ -14383,34 +16404,173 @@ The images can be removed again with \\[org-ctrl-c-ctrl-c]."
   (org-defkey org-mode-map 'button3   'popup-mode-menu))
 
 
+(defconst org-speed-commands-default
+  '(
+    ("Outline Navigation")
+    ("n" . (org-speed-move-safe 'outline-next-visible-heading))
+    ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
+    ("f" . (org-speed-move-safe 'org-forward-same-level))
+    ("b" . (org-speed-move-safe 'org-backward-same-level))
+    ("u" . (org-speed-move-safe 'outline-up-heading))
+    ("j" . org-goto)
+    ("g" . (org-refile t))
+    ("Outline Visibility")
+    ("c" . org-cycle)
+    ("C" . org-shifttab)
+    (" " . org-display-outline-path)
+    ("Outline Structure Editing")
+    ("U" . org-shiftmetaup)
+    ("D" . org-shiftmetadown)
+    ("r" . org-metaright)
+    ("l" . org-metaleft)
+    ("R" . org-shiftmetaright)
+    ("L" . org-shiftmetaleft)
+    ("i" . (progn (forward-char 1) (call-interactively
+                                   'org-insert-heading-respect-content)))
+    ("^" . org-sort)
+    ("w" . org-refile)
+    ("a" . org-archive-subtree-default-with-confirmation)
+    ("." . org-mark-subtree)
+    ("Clock Commands")
+    ("I" . org-clock-in)
+    ("O" . org-clock-out)
+    ("Meta Data Editing")
+    ("t" . org-todo)
+    ("0" . (org-priority ?\ ))
+    ("1" . (org-priority ?A))
+    ("2" . (org-priority ?B))
+    ("3" . (org-priority ?C))
+    (";" . org-set-tags-command)
+    ("e" . org-set-effort)
+    ("Agenda Views etc")
+    ("v" . org-agenda)
+    ("/" . org-sparse-tree)
+    ("Misc")
+    ("o" . org-open-at-point)
+    ("?" . org-speed-command-help)
+    ("<" . (org-agenda-set-restriction-lock 'subtree))
+    (">" . (org-agenda-remove-restriction-lock))
+    )
+  "The default speed commands.")
+
+(defun org-print-speed-command (e)
+  (if (> (length (car e)) 1)
+      (progn
+       (princ "\n")
+       (princ (car e))
+       (princ "\n")
+       (princ (make-string (length (car e)) ?-))
+       (princ "\n"))
+    (princ (car e))
+    (princ "   ")
+    (if (symbolp (cdr e))
+       (princ (symbol-name (cdr e)))
+      (prin1 (cdr e)))
+    (princ "\n")))
+
+(defun org-speed-command-help ()
+  "Show the available speed commands."
+  (interactive)
+  (if (not org-use-speed-commands)
+      (error "Speed commands are not activated, customize `org-use-speed-commands'")
+    (with-output-to-temp-buffer "*Help*"
+      (princ "User-defined Speed commands\n===========================\n")
+      (mapc 'org-print-speed-command org-speed-commands-user)
+      (princ "\n")
+      (princ "Built-in Speed commands\n=======================\n")
+      (mapc 'org-print-speed-command org-speed-commands-default))
+    (with-current-buffer "*Help*"
+      (setq truncate-lines t))))
+
+(defun org-speed-move-safe (cmd)
+  "Execute CMD, but make sure that the cursor always ends up in a headline.
+If not, return to the original position and throw an error."
+  (interactive)
+  (let ((pos (point)))
+    (call-interactively cmd)
+    (unless (and (bolp) (org-on-heading-p))
+      (goto-char pos)
+      (error "Boundary reached while executing %s" cmd))))
+
 (defvar org-self-insert-command-undo-counter 0)
 
 (defvar org-table-auto-blank-field) ; defined in org-table.el
+(defvar org-speed-command nil)
+
+(defun org-speed-command-default-hook (keys)
+  "Hook for activating single-letter speed commands.
+`org-speed-commands-default' specifies a minimal command set. Use
+`org-speed-commands-user' for further customization."
+  (when (or (and (bolp) (looking-at outline-regexp))
+           (and (functionp org-use-speed-commands)
+                (funcall org-use-speed-commands)))
+    (cdr (assoc keys (append org-speed-commands-user
+                            org-speed-commands-default)))))
+
+(defun org-babel-speed-command-hook (keys)
+  "Hook for activating single-letter code block commands."
+  (when (and (bolp) (looking-at org-babel-src-block-regexp))
+    (cdr (assoc keys org-babel-key-bindings))))
+
+(defcustom org-speed-command-hook
+  '(org-speed-command-default-hook org-babel-speed-command-hook)
+  "Hook for activating speed commands at strategic locations.
+Hook functions are called in sequence until a valid handler is
+found.
+
+Each hook takes a single argument, a user-pressed command key
+which is also a `self-insert-command' from the global map.
+
+Within the hook, examine the cursor position and the command key
+and return nil or a valid handler as appropriate. Handler could
+be one of an interactive command, a function, or a form.
+
+Set `org-use-speed-commands' to non-nil value to enable this
+hook. The default setting is `org-speed-command-default-hook'."
+  :group 'org-structure
+  :type 'hook)
+
 (defun org-self-insert-command (N)
   "Like `self-insert-command', use overwrite-mode for whitespace in tables.
 If the cursor is in a table looking at whitespace, the whitespace is
 overwritten, and the table is not marked as requiring realignment."
   (interactive "p")
-  (if (and
-       (org-table-p)
-       (progn
-        ;; check if we blank the field, and if that triggers align
-        (and (featurep 'org-table) org-table-auto-blank-field
-             (member last-command
-                     '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
-             (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]*  |"))
-                 ;; got extra space, this field does not determine column width
-                 (let (org-table-may-need-update) (org-table-blank-field))
+  (cond
+   ((and org-use-speed-commands
+        (setq org-speed-command
+              (run-hook-with-args-until-success
+               'org-speed-command-hook (this-command-keys))))
+    (cond
+     ((commandp org-speed-command)
+      (setq this-command org-speed-command)
+      (call-interactively org-speed-command))
+     ((functionp org-speed-command)
+      (funcall org-speed-command))
+     ((and org-speed-command (listp org-speed-command))
+      (eval org-speed-command))
+     (t (let (org-use-speed-commands)
+         (call-interactively 'org-self-insert-command)))))
+   ((and
+     (org-table-p)
+     (progn
+       ;; check if we blank the field, and if that triggers align
+       (and (featurep 'org-table) org-table-auto-blank-field
+           (member last-command
+                   '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
+           (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]*  |"))
+               ;; got extra space, this field does not determine column width
+               (let (org-table-may-need-update) (org-table-blank-field))
                ;; no extra space, this field may determine column width
-               (org-table-blank-field)))
-        t)
-       (eq N 1)
-       (looking-at "[^|\n]*  |"))
-      (let (org-table-may-need-update)
-       (goto-char (1- (match-end 0)))
-       (delete-backward-char 1)
-       (goto-char (match-beginning 0))
-       (self-insert-command N))
+             (org-table-blank-field)))
+       t)
+     (eq N 1)
+     (looking-at "[^|\n]*  |"))
+    (let (org-table-may-need-update)
+      (goto-char (1- (match-end 0)))
+      (delete-backward-char 1)
+      (goto-char (match-beginning 0))
+      (self-insert-command N)))
+   (t
     (setq org-table-may-need-update t)
     (self-insert-command N)
     (org-fix-tags-on-the-fly)
@@ -14424,7 +16584,7 @@ overwritten, and the table is not marked as requiring realignment."
                 (not (cadr buffer-undo-list)) ; remove nil entry
                 (setcdr buffer-undo-list (cddr buffer-undo-list)))
            (setq org-self-insert-command-undo-counter
-                 (1+ org-self-insert-command-undo-counter)))))))
+                 (1+ org-self-insert-command-undo-counter))))))))
 
 (defun org-fix-tags-on-the-fly ()
   (when (and (equal (char-after (point-at-bol)) ?*)
@@ -14446,9 +16606,11 @@ because, in this case the deletion might narrow the column."
            (noalign (looking-at "[^|\n\r]*  |"))
            (c org-table-may-need-update))
        (backward-delete-char N)
-       (skip-chars-forward "^|")
-       (insert " ")
-       (goto-char (1- pos))
+       (if (not overwrite-mode)
+           (progn
+             (skip-chars-forward "^|")
+             (insert " ")
+             (goto-char (1- pos))))
        ;; noalign: if there were two spaces at the end, this field
        ;; does not determine the width of the column.
        (if noalign (setq org-table-may-need-update c)))
@@ -14535,8 +16697,9 @@ See `org-ctrl-c-ctrl-c-hook' for more information.
 This hook runs as the first action when TAB is pressed, even before
 `org-cycle' messes around with the `outline-regexp' to cater for
 inline tasks and plain list item folding.
-If any function in this hook returns t, not other actions like table
-field motion visibility cycling will be done.")
+If any function in this hook returns t, any other actions that
+would have been caused by TAB (such as table field motion or visibility
+cycling) will not occur.")
 
 (defvar org-tab-after-check-for-table-hook nil
   "Hook for functions to attach themselves to TAB.
@@ -14554,6 +16717,12 @@ This hook runs after it has been established that not table field motion and
 not visibility should be done because of current context.  This is probably
 the place where a package like yasnippets can hook in.")
 
+(defvar org-tab-before-tab-emulation-hook nil
+  "Hook for functions to attach themselves to TAB.
+See `org-ctrl-c-ctrl-c-hook' for more information.
+This hook runs after every other options for TAB have been exhausted, but
+before indentation and \t insertion takes place.")
+
 (defvar org-metaleft-hook nil
   "Hook for functions attaching themselves to `M-left'.
 See `org-ctrl-c-ctrl-c-hook' for more information.")
@@ -14581,6 +16750,34 @@ See `org-ctrl-c-ctrl-c-hook' for more information.")
 (defvar org-metareturn-hook nil
   "Hook for functions attaching themselves to `M-RET'.
 See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-shiftup-hook nil
+  "Hook for functions attaching themselves to `S-up'.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-shiftup-final-hook nil
+  "Hook for functions attaching themselves to `S-up'.
+This one runs after all other options except shift-select have been excluded.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-shiftdown-hook nil
+  "Hook for functions attaching themselves to `S-down'.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-shiftdown-final-hook nil
+  "Hook for functions attaching themselves to `S-down'.
+This one runs after all other options except shift-select have been excluded.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-shiftleft-hook nil
+  "Hook for functions attaching themselves to `S-left'.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-shiftleft-final-hook nil
+  "Hook for functions attaching themselves to `S-left'.
+This one runs after all other options except shift-select have been excluded.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-shiftright-hook nil
+  "Hook for functions attaching themselves to `S-right'.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-shiftright-final-hook nil
+  "Hook for functions attaching themselves to `S-right'.
+This one runs after all other options except shift-select have been excluded.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
 
 (defun org-modifier-cursor-error ()
   "Throw an error, a modified cursor command was applied in wrong context."
@@ -14589,8 +16786,8 @@ See `org-ctrl-c-ctrl-c-hook' for more information.")
 (defun org-shiftselect-error ()
   "Throw an error because Shift-Cursor command was applied in wrong context."
   (if (and (boundp 'shift-select-mode) shift-select-mode)
-      (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
-    (error "This command works only in special context like headlines or timestamps.")))
+      (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
+    (error "This command works only in special context like headlines or timestamps")))
 
 (defun org-call-for-shift-select (cmd)
   (let ((this-command-keys-shift-translated t))
@@ -14605,9 +16802,10 @@ See the individual commands for more information."
   (cond
    ((org-at-table-p) (call-interactively 'org-table-previous-field))
    ((integerp arg)
-    (message "Content view to level: %d" arg)
-    (org-content (prefix-numeric-value arg))
-    (setq org-cycle-global-status 'overview))
+    (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
+      (message "Content view to level: %d" arg)
+      (org-content (prefix-numeric-value arg2))
+      (setq org-cycle-global-status 'overview)))
    (t (call-interactively 'org-global-cycle))))
 
 (defun org-shiftmetaleft ()
@@ -14620,7 +16818,7 @@ See the individual commands for more information."
    ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
    ((org-at-table-p) (call-interactively 'org-table-delete-column))
    ((org-on-heading-p) (call-interactively 'org-promote-subtree))
-   ((org-at-item-p) (call-interactively 'org-outdent-item))
+   ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
    (t (org-modifier-cursor-error))))
 
 (defun org-shiftmetaright ()
@@ -14633,7 +16831,7 @@ See the individual commands for more information."
    ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
    ((org-at-table-p) (call-interactively 'org-table-insert-column))
    ((org-on-heading-p) (call-interactively 'org-demote-subtree))
-   ((org-at-item-p) (call-interactively 'org-indent-item))
+   ((org-at-item-p) (call-interactively 'org-indent-item-tree))
    (t (org-modifier-cursor-error))))
 
 (defun org-shiftmetaup (&optional arg)
@@ -14662,6 +16860,10 @@ commands for more information."
    ((org-at-item-p) (call-interactively 'org-move-item-down))
    (t (org-modifier-cursor-error))))
 
+(defsubst org-hidden-tree-error ()
+  (error
+   "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
+
 (defun org-metaleft (&optional arg)
   "Promote heading or move table column to left.
 Calls `org-do-promote' or `org-table-move-column', depending on context.
@@ -14676,12 +16878,14 @@ See the individual commands for more information."
             (save-excursion
               (goto-char (region-beginning))
               (org-on-heading-p))))
+    (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
     (call-interactively 'org-do-promote))
    ((or (org-at-item-p)
        (and (org-region-active-p)
             (save-excursion
               (goto-char (region-beginning))
               (org-at-item-p))))
+    (when (org-check-for-hidden 'items) (org-hidden-tree-error))
     (call-interactively 'org-outdent-item))
    (t (call-interactively 'backward-word))))
 
@@ -14699,15 +16903,44 @@ See the individual commands for more information."
             (save-excursion
               (goto-char (region-beginning))
               (org-on-heading-p))))
+    (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
     (call-interactively 'org-do-demote))
    ((or (org-at-item-p)
        (and (org-region-active-p)
             (save-excursion
               (goto-char (region-beginning))
               (org-at-item-p))))
+    (when (org-check-for-hidden 'items) (org-hidden-tree-error))
     (call-interactively 'org-indent-item))
    (t (call-interactively 'forward-word))))
 
+(defun org-check-for-hidden (what)
+  "Check if there are hidden headlines/items in the current visual line.
+WHAT can be either `headlines' or `items'.  If the current line is
+an outline or item heading and it has a folded subtree below it,
+this function returns t, nil otherwise."
+  (let ((re (cond
+            ((eq what 'headlines) (concat "^" org-outline-regexp))
+            ((eq what 'items) (concat "^" (org-item-re t)))
+            (t (error "This should not happen"))))
+       beg end)
+    (save-excursion
+      (catch 'exit
+       (unless (org-region-active-p)
+         (setq beg (point-at-bol))
+         (beginning-of-line 2)
+         (while (and (not (eobp)) ;; this is like `next-line'
+                     (get-char-property (1- (point)) 'invisible))
+           (beginning-of-line 2))
+         (setq end (point))
+         (goto-char beg)
+         (goto-char (point-at-eol))
+         (setq end (max end (point)))
+         (while (re-search-forward re end t)
+           (if (get-char-property (match-beginning 0) 'invisible)
+               (throw 'exit t))))
+       nil))))
+
 (defun org-metaup (&optional arg)
   "Move subtree up or move table row up.
 Calls `org-move-subtree-up' or `org-table-move-row' or
@@ -14740,6 +16973,7 @@ 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
+   ((run-hook-with-args-until-success 'org-shiftup-hook))
    ((and org-support-shift-select (org-region-active-p))
     (org-call-for-shift-select 'previous-line))
    ((org-at-timestamp-p t)
@@ -14752,6 +16986,7 @@ depending on context.  See the individual commands for more information."
    ((and (not org-support-shift-select) (org-at-item-p))
     (call-interactively 'org-previous-item))
    ((org-clocktable-try-shift 'up arg))
+   ((run-hook-with-args-until-success 'org-shiftup-final-hook))
    (org-support-shift-select
     (org-call-for-shift-select 'previous-line))
    (t (org-shiftselect-error))))
@@ -14762,6 +16997,7 @@ 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
+   ((run-hook-with-args-until-success 'org-shiftdown-hook))
    ((and org-support-shift-select (org-region-active-p))
     (org-call-for-shift-select 'next-line))
    ((org-at-timestamp-p t)
@@ -14774,6 +17010,7 @@ depending on context.  See the individual commands for more information."
    ((and (not org-support-shift-select) (org-at-item-p))
     (call-interactively 'org-next-item))
    ((org-clocktable-try-shift 'down arg))
+   ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
    (org-support-shift-select
     (org-call-for-shift-select 'next-line))
    (t (org-shiftselect-error))))
@@ -14789,6 +17026,7 @@ Depending on context, this does one of the following:
 - on a clocktable definition line, move time block into the future"
   (interactive "P")
   (cond
+   ((run-hook-with-args-until-success 'org-shiftright-hook))
    ((and org-support-shift-select (org-region-active-p))
     (org-call-for-shift-select 'forward-char))
    ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
@@ -14808,6 +17046,7 @@ Depending on context, this does one of the following:
         (org-at-property-p))
     (call-interactively 'org-property-next-allowed-value))
    ((org-clocktable-try-shift 'right arg))
+   ((run-hook-with-args-until-success 'org-shiftright-final-hook))
    (org-support-shift-select
     (org-call-for-shift-select 'forward-char))
    (t (org-shiftselect-error))))
@@ -14823,6 +17062,7 @@ Depending on context, this does one of the following:
 - on a clocktable definition line, move time block into the past"
   (interactive "P")
   (cond
+   ((run-hook-with-args-until-success 'org-shiftleft-hook))
    ((and org-support-shift-select (org-region-active-p))
     (org-call-for-shift-select 'backward-char))
    ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
@@ -14842,6 +17082,7 @@ Depending on context, this does one of the following:
         (org-at-property-p))
     (call-interactively 'org-property-previous-allowed-value))
    ((org-clocktable-try-shift 'left arg))
+   ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
    (org-support-shift-select
     (org-call-for-shift-select 'backward-char))
    (t (org-shiftselect-error))))
@@ -14904,25 +17145,38 @@ See the individual commands for more information."
       (org-table-paste-rectangle)
     (org-paste-subtree arg)))
 
-(defun org-edit-special ()
+(defun org-edit-special (&optional arg)
   "Call a special editor for the stuff at point.
 When at a table, call the formula editor with `org-table-edit-formulas'.
 When at the first line of an src example, call `org-edit-src-code'.
 When in an #+include line, visit the include file.  Otherwise call
 `ffap' to visit the file at point."
   (interactive)
-  (cond
-   ((org-at-table-p)
-    (call-interactively 'org-table-edit-formulas))
+  ;; possibly prep session before editing source
+  (when arg
+    (let* ((info (org-babel-get-src-block-info))
+           (lang (nth 0 info))
+           (params (nth 2 info))
+           (session (cdr (assoc :session params))))
+      (when (and info session) ;; we are in a source-code block with a session
+        (funcall
+         (intern (concat "org-babel-prep-session:" lang)) session params))))
+  (cond ;; proceed with `org-edit-special'
    ((save-excursion
       (beginning-of-line 1)
       (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
     (find-file (org-trim (match-string 1))))
    ((org-edit-src-code))
    ((org-edit-fixed-width-region))
+   ((org-at-table.el-p)
+    (org-edit-src-code))
+   ((or (org-at-table-p)
+       (save-excursion
+         (beginning-of-line 1)
+         (looking-at "[ \t]*#\\+TBLFM:")))
+    (call-interactively 'org-table-edit-formulas))
    (t (call-interactively 'ffap))))
 
-
 (defun org-ctrl-c-ctrl-c (&optional arg)
   "Set tags in headline, or update according to changed information at point.
 
@@ -14952,21 +17206,21 @@ This command does many different things, depending on context:
 
 - If the cursor is a the beginning of a dynamic block, update it.
 
-- If the cursor is inside a table created by the table.el package,
-  activate that table.
+- If the current buffer is a capture buffer, close note and file it.
 
-- If the current buffer is a remember buffer, close note and file
-  it.  A prefix argument of 1 files to the default location
-  without further interaction.  A prefix argument of 2 files to
-  the currently clocking task.
-
-- If the cursor is on a <<<target>>>, update radio targets and corresponding
-  links in this buffer.
+- If the cursor is on a <<<target>>>, update radio targets and
+  corresponding links in this buffer.
 
 - If the cursor is on a numbered item in a plain list, renumber the
   ordered list.
 
-- If the cursor is on a checkbox, toggle it."
+- If the cursor is on a checkbox, toggle it.
+
+- If the cursor is on a code block, evaluate it.  The variable
+  `org-confirm-babel-evaluate' can be used to control prompting
+  before code block evaluation, by default every code block
+  evaluation requires confirmation.  Code block evaluation can be
+  inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
   (interactive "P")
   (let  ((org-enable-table-editor t))
     (cond
@@ -14981,7 +17235,8 @@ This command does many different things, depending on context:
           (fboundp org-finish-function))
       (funcall org-finish-function))
      ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
-     ((org-at-property-p)
+     ((or (looking-at org-property-start-re)
+         (org-at-property-p))
       (call-interactively 'org-property-action))
      ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
      ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
@@ -14989,26 +17244,26 @@ This command does many different things, depending on context:
       (call-interactively 'org-update-statistics-cookies))
      ((org-on-heading-p) (call-interactively 'org-set-tags))
      ((org-at-table.el-p)
-      (require 'table)
-      (beginning-of-line 1)
-      (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
-      (call-interactively 'table-recognize-table))
+      (message "Use C-c ' to edit table.el tables"))
      ((org-at-table-p)
       (org-table-maybe-eval-formula)
       (if arg
          (call-interactively 'org-table-recalculate)
        (org-table-maybe-recalculate-line))
-      (call-interactively 'org-table-align))
+      (call-interactively 'org-table-align)
+      (orgtbl-send-table 'maybe))
      ((or (org-footnote-at-reference-p)
          (org-footnote-at-definition-p))
       (call-interactively 'org-footnote-action))
      ((org-at-item-checkbox-p)
-      (call-interactively 'org-toggle-checkbox))
+      (call-interactively 'org-list-repair)
+      (call-interactively 'org-toggle-checkbox)
+      (org-list-send-list 'maybe))
      ((org-at-item-p)
-      (if arg
-         (call-interactively 'org-toggle-checkbox)
-       (call-interactively 'org-maybe-renumber-ordered-list)))
-     ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
+      (call-interactively 'org-list-repair)
+      (when arg (call-interactively 'org-toggle-checkbox))
+      (org-list-send-list 'maybe))
+     ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
       ;; Dynamic block
       (beginning-of-line 1)
       (save-excursion (org-update-dblock)))
@@ -15022,14 +17277,14 @@ This command does many different things, depending on context:
          (beginning-of-line 1)
          (skip-chars-backward " \r\n\t")
          (if (org-at-table-p)
-             (org-call-with-arg 'org-table-recalculate t))))
+             (org-call-with-arg 'org-table-recalculate (or arg t)))))
        (t
-;      (org-set-regexps-and-options)
-;      (org-restart-font-lock)
-       (let ((org-inhibit-startup t)) (org-mode-restart))
+       (let ((org-inhibit-startup-visibility-stuff t)
+             (org-startup-align-all-tables nil))
+         (org-save-outline-visibility 'use-markers (org-mode-restart)))
        (message "Local setup has been refreshed"))))
      ((org-clock-update-time-maybe))
-     (t (error "C-c C-c can do nothing useful at this location.")))))
+     (t (error "C-c C-c can do nothing useful at this location")))))
 
 (defun org-mode-restart ()
   "Restart Org-mode, to scan again for special lines.
@@ -15042,7 +17297,9 @@ Also updates the keyword regular expressions."
   "If this is a Note buffer, abort storing the note.  Else call `show-branches'."
   (interactive)
   (if (not org-finish-function)
-      (call-interactively 'show-branches)
+      (progn
+       (hide-subtree)
+       (call-interactively 'show-branches))
     (let ((org-note-abort t))
       (funcall org-finish-function))))
 
@@ -15061,7 +17318,7 @@ See the individual commands for more information."
     (call-interactively 'org-open-at-point))
    ((and (org-at-heading-p)
         (looking-at
-         (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
+         (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
     (org-show-entry)
     (end-of-line 1)
     (newline))
@@ -15127,21 +17384,21 @@ If the first line is normal text, add an item bullet to each line."
          ;; We already have items, de-itemize
          (while (< (setq l (1+ l)) l2)
            (when (org-at-item-p)
-             (goto-char (match-beginning 2))
-             (delete-region (match-beginning 2) (match-end 2))
-             (and (looking-at "[ \t]+") (replace-match "")))
+             (skip-chars-forward " \t")
+             (delete-region (point) (match-end 0)))
            (beginning-of-line 2))
        (if (org-on-heading-p)
            ;; Headings, convert to items
            (while (< (setq l (1+ l)) l2)
              (if (looking-at org-outline-regexp)
-                 (replace-match "- " t t))
+                 (replace-match (org-list-bullet-string "-") t t))
              (beginning-of-line 2))
          ;; normal lines, turn them into items
          (while (< (setq l (1+ l)) l2)
            (unless (org-at-item-p)
              (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
-                 (replace-match "\\1- \\2")))
+                 (replace-match
+                  (concat "\\1" (org-list-bullet-string "-") "\\2"))))
            (beginning-of-line 2)))))))
 
 (defun org-toggle-heading (&optional nstars)
@@ -15320,21 +17577,11 @@ See the individual commands for more information."
      ["Footnote new/jump" org-footnote-action t]
      ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
     ("Archive"
-     ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
-;     ["Check and Tag Children" (org-toggle-archive-tag (4))
-;      :active t :keys "C-u C-c C-x C-a"]
-     ["Sparse trees open ARCHIVE trees"
-      (setq org-sparse-tree-open-archived-trees
-           (not org-sparse-tree-open-archived-trees))
-      :style toggle :selected org-sparse-tree-open-archived-trees]
-     ["Cycling opens ARCHIVE trees"
-      (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
-      :style toggle :selected org-cycle-open-archived-trees]
+     ["Archive (default method)" org-archive-subtree-default t]
      "--"
-     ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
-     ["Move Subtree to Archive" org-advertized-archive-subtree t]
- ;    ["Check and Move Children" (org-archive-subtree '(4))
- ;     :active t :keys "C-u C-c C-x C-s"]
+     ["Move Subtree to Archive file" org-advertized-archive-subtree t]
+     ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
+     ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
      )
     "--"
     ("Hyperlinks"
@@ -15347,7 +17594,7 @@ See the individual commands for more information."
      ["Previous link" org-previous-link t]
      "--"
      ["Descriptive Links"
-      (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
+      (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
       :style radio
       :selected (member '(org-link) buffer-invisibility-spec)]
      ["Literal Links"
@@ -15361,11 +17608,11 @@ See the individual commands for more information."
      ("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" pcomplete (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]
+     ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
+     ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
      "--"
      ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
       :selected org-enforce-todo-dependencies :style toggle :active t]
@@ -15453,13 +17700,14 @@ See the individual commands for more information."
       (org-inside-LaTeX-fragment-p)]
      ["Insert citation" org-reftex-citation t]
      "--"
-     ["Export LaTeX fragments as images"
-      (if (featurep 'org-exp)
-         (setq org-export-with-LaTeX-fragments
-               (not org-export-with-LaTeX-fragments))
-       (require 'org-exp))
-      :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
-                                  org-export-with-LaTeX-fragments)])
+     ["Template for BEAMER" org-insert-beamer-options-template t])
+    "--"
+    ("MobileOrg"
+     ["Push Files and Views" org-mobile-push t]
+     ["Get Captured and Flagged" org-mobile-pull t]
+     ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
+     "--"
+     ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
     "--"
     ("Documentation"
      ["Show Version" org-version t]
@@ -15537,7 +17785,11 @@ what in fact did happen.  You don't know how to make a good report?  See
      http://orgmode.org/manual/Feedback.html#Feedback
 
 Your bug report will be posted to the Org-mode mailing list.
-------------------------------------------------------------------------")))
+------------------------------------------------------------------------")
+    (save-excursion
+      (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
+         (replace-match "\\1Bug: \\3 [\\2]")))))
+
 
 (defun org-install-agenda-files-menu ()
   (let ((bl (buffer-list)))
@@ -15581,8 +17833,18 @@ With prefix arg UNCOMPILED, load the uncompiled versions."
         (dir-org-contrib (ignore-errors
                           (file-name-directory
                            (org-find-library-name "org-contribdir"))))
+        (babel-files
+         (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
+                 (append (list nil "comint" "eval" "exp" "keys"
+                                   "lob" "ref" "table" "tangle")
+                         (delq nil
+                               (mapcar
+                                (lambda (lang)
+                                  (when (cdr lang) (symbol-name (car lang))))
+                                org-babel-load-languages)))))
         (files
          (append (directory-files dir-org t file-re)
+                 babel-files
                  (and dir-org-contrib
                       (directory-files dir-org-contrib t file-re))))
         (remove-re (concat (if (featurep 'xemacs)
@@ -15635,6 +17897,10 @@ With prefix arg UNCOMPILED, load the uncompiled versions."
 
 ;;; Generally useful functions
 
+(defun org-get-at-bol (property)
+  "Get text property PROPERTY at beginning of line."
+  (get-text-property (point-at-bol) property))
+
 (defun org-find-text-property-in-string (prop s)
   "Return the first non-nil value of property PROP in string S."
   (or (get-text-property 0 prop s)
@@ -15645,9 +17911,7 @@ With prefix arg UNCOMPILED, load the uncompiled versions."
   "Display the given MESSAGE as a warning."
   (if (fboundp 'display-warning)
       (display-warning 'org message
-                       (if (featurep 'xemacs)
-                           'warning
-                         :warning))
+                       (if (featurep 'xemacs) 'warning :warning))
     (let ((buf (get-buffer-create "*Org warnings*")))
       (with-current-buffer buf
         (goto-char (point-max))
@@ -15661,6 +17925,17 @@ With prefix arg UNCOMPILED, load the uncompiled versions."
   "Is point in a line starting with `#'?"
   (equal (char-after (point-at-bol)) ?#))
 
+(defun org-in-indented-comment-line ()
+  "Is point in a line starting with `#' after some white space?"
+  (save-excursion
+    (save-match-data
+      (goto-char (point-at-bol))
+      (looking-at "[ \t]*#"))))
+
+(defun org-in-verbatim-emphasis ()
+  (save-match-data
+    (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
+
 (defun org-goto-marker-or-bmk (marker &optional bookmark)
   "Go to MARKER, widen if necessary.  When marker is not live, try BOOKMARK."
   (if (and marker (marker-buffer marker)
@@ -15718,6 +17993,23 @@ upon the next fontification round."
       (setq l (- l (get-text-property b 'org-dwidth-n s))))
     l))
 
+(defun org-shorten-string (s maxlength)
+  "Shorten string S so tht it is no longer than MAXLENGTH characters.
+If the string is shorter or has length MAXLENGTH, just return the
+original string.  If it is longer, the functions finds a space in the
+string, breaks this string off at that locations and adds three dots
+as ellipsis.  Including the ellipsis, the string will not be longer
+than MAXLENGTH.  If finding a good breaking point in the string does
+not work, the string is just chopped off in the middle of a word
+if necessary."
+  (if (<= (length s) maxlength)
+      s
+    (let* ((n (max (- maxlength 4) 1))
+          (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
+      (if (string-match re s)
+         (concat (match-string 1 s) "...")
+       (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
+
 (defun org-get-indentation (&optional line)
   "Get the indentation of the current line, interpreting tabs.
 When LINE is given, assume it represents a line and compute its indentation."
@@ -15779,6 +18071,19 @@ N may optionally be the number of spaces to remove."
        (end-of-line 1))
       min)))
 
+(defun org-fill-template (template alist)
+  "Find each %key of ALIST in TEMPLATE and replace it."
+  (let ((case-fold-search nil)
+       entry key value)
+    (setq alist (sort (copy-sequence alist)
+                     (lambda (a b) (< (length (car a)) (length (car b))))))
+    (while (setq entry (pop alist))
+      (setq template
+           (replace-regexp-in-string
+            (concat "%" (regexp-quote (car entry)))
+            (cdr entry) template t t)))
+    template))
+
 (defun org-base-buffer (buffer)
   "Return the base buffer of BUFFER, if it has one.  Else return the buffer."
   (if (not buffer)
@@ -15907,7 +18212,7 @@ and :keyword."
        (push (org-point-in-group p 2 :todo-keyword) clist)
        (push (org-point-in-group p 4 :tags) clist))
       (goto-char p)
-      (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
+      (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
       (if (looking-at "\\[#[A-Z0-9]\\]")
          (push (org-point-in-group p 0 :priority) clist)))
 
@@ -15951,11 +18256,11 @@ and :keyword."
                         (mapcar
                          (lambda (x)
                            (if (memq x org-latex-fragment-image-overlays) x))
-                         (org-overlays-at (point))))))
+                         (overlays-at (point))))))
       (push (list :latex-fragment
-                 (org-overlay-start o) (org-overlay-end o)) clist)
+                 (overlay-start o) (overlay-end o)) clist)
       (push (list :latex-preview
-                 (org-overlay-start o) (org-overlay-end o)) clist))
+                 (overlay-start o) (overlay-end o)) clist))
      ((org-inside-LaTeX-fragment-p)
       ;; FIXME: positions wrong.
       (push (list :latex-fragment (point) (point)) clist)))
@@ -15993,6 +18298,24 @@ really on, so that the block visually is on the match."
              (throw 'exit t)))
        nil))))
 
+(defun org-in-regexps-block-p (start-re end-re &optional bound)
+  "Return t if the current point is between matches of START-RE and END-RE.
+This will also return t if point is on one of the two matches or
+in an unfinished block. END-RE can be a string or a form
+returning a string.
+
+An optional third argument bounds the search for START-RE. It
+defaults to previous heading or `point-min'."
+  (let ((pos (point))
+       (limit (or bound (save-excursion (outline-previous-heading)))))
+    (save-excursion
+      ;; we're on a block when point is on start-re...
+      (or (org-at-regexp-p start-re)
+         ;; ... or start-re can be found above...
+         (and (re-search-backward start-re limit t)
+              ;; ... but no end-re between start-re and point.
+              (not (re-search-forward (eval end-re) pos t)))))))
+
 (defun org-occur-in-agenda-files (regexp &optional nlines)
   "Call `multi-occur' with buffers for all agenda files."
   (interactive "sOrg-files matching: \np")
@@ -16008,7 +18331,12 @@ really on, so that the block visually is on the match."
        (add-to-list 'files f 'append)
        (add-to-list 'tnames (file-truename f) 'append)))
     (multi-occur
-     (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
+     (mapcar (lambda (x)
+              (with-current-buffer
+                  (or (get-file-buffer x) (find-file-noselect x))
+                (widen)
+                (current-buffer)))
+            files)
      regexp)))
 
 (if (boundp 'occur-mode-find-occurrence-hook)
@@ -16055,6 +18383,33 @@ for the search purpose."
     (setq list (delete (pop elts) list)))
   list)
 
+(defun org-count (cl-item cl-seq)
+  "Count the number of occurrences of ITEM in SEQ.
+Taken from `count' in cl-seq.el with all keyword arguments removed."
+  (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0)  cl-x)
+    (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
+    (while (< cl-start cl-end)
+      (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
+      (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
+      (setq cl-start (1+ cl-start)))
+    cl-count))
+
+(defun org-remove-if (predicate seq)
+  "Remove everything from SEQ that fulfills PREDICATE."
+  (let (res e)
+    (while seq
+      (setq e (pop seq))
+      (if (not (funcall predicate e)) (push e res)))
+    (nreverse res)))
+
+(defun org-remove-if-not (predicate seq)
+  "Remove everything from SEQ that does not fulfill PREDICATE."
+  (let (res e)
+    (while seq
+      (setq e (pop seq))
+      (if (funcall predicate e) (push e res)))
+    (nreverse res)))
+
 (defun org-back-over-empty-lines ()
   "Move backwards over whitespace, to the beginning of the first empty line.
 Returns the number of empty lines passed."
@@ -16070,7 +18425,7 @@ Returns the number of empty lines passed."
 (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
-match.  If the match group does ot exist or point is not inside it,
+match.  If the match group does not exist or point is not inside it,
 return nil."
   (and (match-beginning group)
        (>= point (match-beginning group))
@@ -16081,7 +18436,8 @@ return nil."
 
 (defun org-switch-to-buffer-other-window (&rest args)
   "Switch to buffer in a second window on the current frame.
-In particular, do not allow pop-up frames."
+In particular, do not allow pop-up frames.
+Returns the newly created buffer."
   (let (pop-up-frames special-display-buffer-names special-display-regexps
                      special-display-function)
     (apply 'switch-to-buffer-other-window args)))
@@ -16132,17 +18488,27 @@ TABLE is an association list with keys like \"%a\" and string values.
 The sequences in STRING may contain normal field width and padding information,
 for example \"%-5s\".  Replacements happen in the sequence given by TABLE,
 so values can contain further %-escapes if they are define later in TABLE."
-  (let ((case-fold-search nil)
-       e re rpl)
-    (while (setq e (pop table))
+  (let ((tbl (copy-alist table))
+       (case-fold-search nil)
+        (pchg 0)
+        e re rpl)
+    (while (setq e (pop tbl))
       (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
+      (when (and (cdr e) (string-match re (cdr e)))
+        (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
+              (safe "SREF"))
+          (add-text-properties 0 3 (list 'sref sref) safe)
+          (setcdr e (replace-match safe t t (cdr e)))))
       (while (string-match re string)
-       (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
-                         (cdr e)))
-       (setq string (replace-match rpl t t string))))
+        (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
+                          (cdr e)))
+        (setq string (replace-match rpl t t string))))
+    (while (setq pchg (next-property-change pchg string))
+      (let ((sref (get-text-property pchg 'sref string)))
+       (when (and sref (string-match "SREF" string pchg))
+         (setq string (replace-match sref t t string)))))
     string))
 
-
 (defun org-sublist (list start end)
   "Return a section of LIST, from START to END.
 Counting starts at 1."
@@ -16214,92 +18580,146 @@ which make use of the date at the cursor."
   (message
    "Entry marked for action; press `k' at desired date in agenda or calendar"))
 
+(defun org-mark-subtree ()
+  "Mark the current subtree.
+This puts point at the start of the current subtree, and mark at the end.
+
+If point is in an inline task, mark that task instead."
+  (interactive)
+  (let ((inline-task-p
+        (and (featurep 'org-inlinetask)
+             (org-inlinetask-in-task-p)))
+       (beg))
+    ;; Get beginning of subtree
+    (cond
+     (inline-task-p (org-inlinetask-goto-beginning))
+     ((org-at-heading-p) (beginning-of-line))
+     (t (let ((outline-regexp (org-get-limited-outline-regexp)))
+         (outline-previous-visible-heading 1))))
+    (setq beg (point))
+    ;; Get end of it
+    (if        inline-task-p
+       (org-inlinetask-goto-end)
+      (org-end-of-subtree))
+    ;; Mark zone
+    (push-mark (point) nil t)
+    (goto-char beg)))
+
 ;;; Paragraph filling stuff.
 ;; We want this to be just right, so use the full arsenal.
 
 (defun org-indent-line-function ()
-  "Indent line like previous, but further if previous was headline or item."
+  "Indent line depending on context."
   (interactive)
   (let* ((pos (point))
         (itemp (org-at-item-p))
         (case-fold-search t)
         (org-drawer-regexp (or org-drawer-regexp "\000"))
-        column bpos bcol tpos tcol bullet btype bullet-type)
-    ;; Find the previous relevant line
+        (inline-task-p (and (featurep 'org-inlinetask)
+                            (org-inlinetask-in-task-p)))
+        column bpos bcol tpos tcol)
     (beginning-of-line 1)
     (cond
-     ((looking-at "#") (setq column 0))
+     ;; Comments
+     ((looking-at "# ") (setq column 0))
+     ;; Headings
      ((looking-at "\\*+ ") (setq column 0))
+     ;; Literal examples
+     ((looking-at "[ \t]*:[ \t]")
+      (setq column (org-get-indentation))) ; do nothing
+     ;; Drawers
      ((and (looking-at "[ \t]*:END:")
           (save-excursion (re-search-backward org-drawer-regexp nil t)))
       (save-excursion
        (goto-char (1- (match-beginning 1)))
        (setq column (current-column))))
-     ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
+     ;; Special blocks
+     ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
           (save-excursion
             (re-search-backward
              (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
       (setq column (org-get-indentation (match-string 0))))
+     ((and (not (looking-at "[ \t]*#\\+begin_"))
+          (org-in-regexps-block-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
+      (save-excursion
+       (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
+      (setq column
+           (if (equal (downcase (match-string 1)) "src")
+               ;; src blocks: let `org-edit-src-exit' handle them
+               (org-get-indentation)
+             (org-get-indentation (match-string 0)))))
+     ;; Lists
+     ((org-in-item-p)
+      (org-beginning-of-item)
+      (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\(:?\\[@\\(:?start:\\)?[0-9]+\\][ \t]*\\)?\\[[- X]\\][ \t]*\\|.*? :: \\)?")
+      (setq bpos (match-beginning 1) tpos (match-end 0)
+           bcol (progn (goto-char bpos) (current-column))
+           tcol (progn (goto-char tpos) (current-column)))
+      (if (> tcol (+ bcol org-description-max-indent))
+         (setq tcol (+ bcol 5)))
+      (goto-char pos)
+      (setq column (if itemp (org-get-indentation) tcol)))
+     ;; This line has nothing special, look at the previous relevant
+     ;; line to compute indentation
      (t
       (beginning-of-line 0)
-      (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
-                 (not (looking-at "[ \t]*:END:"))
-                 (not (looking-at org-drawer-regexp)))
-       (beginning-of-line 0))
+      (while (and (not (bobp))
+                 (not (looking-at org-drawer-regexp))
+                 ;; skip comments, verbatim, empty lines, tables,
+                 ;; inline tasks, lists, drawers and blocks
+                 (or (and (looking-at "[ \t]*:END:")
+                          (re-search-backward org-drawer-regexp nil t))
+                     (and (looking-at "[ \t]*#\\+end_")
+                          (re-search-backward "[ \t]*#\\+begin_"nil t))
+                     (looking-at "[ \t]*[\n:#|]")
+                     (and (org-in-item-p) (goto-char (org-list-top-point)))
+                     (and (not inline-task-p)
+                          (featurep 'org-inlinetask)
+                          (org-inlinetask-in-task-p)
+                          (or (org-inlinetask-goto-beginning) t))))
+       (beginning-of-line 0))
       (cond
+       ;; There was an heading above.
        ((looking-at "\\*+[ \t]+")
        (if (not org-adapt-indentation)
            (setq column 0)
          (goto-char (match-end 0))
          (setq column (current-column))))
+       ;; A drawer had started and is unfinished
        ((looking-at org-drawer-regexp)
-         (goto-char (1- (match-beginning 1)))
-         (setq column (current-column)))
-       ((looking-at "\\([ \t]*\\):END:")
-         (goto-char (match-end 1))
-         (setq column (current-column)))
-       ((org-in-item-p)
-       (org-beginning-of-item)
-       (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
-       (setq bpos (match-beginning 1) tpos (match-end 0)
-             bcol (progn (goto-char bpos) (current-column))
-             tcol (progn (goto-char tpos) (current-column))
-             bullet (match-string 1)
-             bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
-       (if (> tcol (+ bcol org-description-max-indent))
-           (setq tcol (+ bcol 5)))
-       (if (not itemp)
-           (setq column tcol)
-         (goto-char pos)
-         (beginning-of-line 1)
-         (if (looking-at "\\S-")
-             (progn
-               (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
-               (setq bullet (match-string 1)
-                     btype (if (string-match "[0-9]" bullet) "n" bullet))
-               (setq column (if (equal btype bullet-type) bcol tcol)))
-           (setq column (org-get-indentation)))))
+       (goto-char (1- (match-beginning 1)))
+       (setq column (current-column)))
+       ;; Else, nothing noticeable found: get indentation and go on.
        (t (setq column (org-get-indentation))))))
+    ;; Now apply indentation and move cursor accordingly
     (goto-char pos)
     (if (<= (current-column) (current-indentation))
        (org-indent-line-to column)
       (save-excursion (org-indent-line-to column)))
+    ;; Special polishing for properties, see `org-property-format'
     (setq column (current-column))
     (beginning-of-line 1)
     (if (looking-at
         "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
-       (replace-match (concat "\\1" (format org-property-format
-                                            (match-string 2) (match-string 3)))
-                      t nil))
+       (replace-match (concat (match-string 1)
+                              (format org-property-format
+                                      (match-string 2) (match-string 3)))
+                      t t))
     (org-move-to-column column)))
 
+(defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
+  "Variable to store copy of `adaptive-fill-regexp'.
+Since `adaptive-fill-regexp' is set to never match, we need to
+store a backup of its value before entering `org-mode' so that
+the functionality can be provided as a fall-back.")
+
 (defun org-set-autofill-regexps ()
   (interactive)
   ;; In the paragraph separator we include headlines, because filling
   ;; text in a line directly attached to a headline would otherwise
   ;; fill the headline as well.
   (org-set-local 'comment-start-skip "^#+[ \t]*")
-  (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[   ]*$\\|[ \t]*[:|]")
+  (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[   ]*$\\|[ \t]*[:|#]")
   ;; The paragraph starter includes hand-formatted lists.
   (org-set-local
    'paragraph-start
@@ -16307,6 +18727,7 @@ which make use of the date at the cursor."
     "\f" "\\|"
     "[         ]*$" "\\|"
     "\\*+ " "\\|"
+    "[ \t]*#" "\\|"
     "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
     "[ \t]*[:|]" "\\|"
     "\\$\\$" "\\|"
@@ -16327,8 +18748,11 @@ which make use of the date at the cursor."
   ;; and fixed-width regions are not wrapped.  That function will pass
   ;; through to `fill-paragraph' when appropriate.
   (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
-  ; Adaptive filling: To get full control, first make sure that
+  ;; Adaptive filling: To get full control, first make sure that
   ;; `adaptive-fill-regexp' never matches.  Then install our own matcher.
+  (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
+    (org-set-local 'org-adaptive-fill-regexp-backup
+                   adaptive-fill-regexp))
   (org-set-local 'adaptive-fill-regexp "\000")
   (org-set-local 'adaptive-fill-function
                 'org-adaptive-fill-function)
@@ -16357,8 +18781,11 @@ which make use of the date at the cursor."
   "Return a fill prefix for org-mode files.
 In particular, this makes sure hanging paragraphs for hand-formatted lists
 work correctly."
-  (cond ((looking-at "#[ \t]+")
-        (match-string 0))
+  (cond
+   ;; Comment line
+   ((looking-at "#[ \t]+")
+    (match-string-no-properties 0))
+   ;; Description list
        ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
         (save-excursion
           (if (> (match-end 1) (+ (match-beginning 1)
@@ -16366,11 +18793,14 @@ work correctly."
               (goto-char (+ (match-beginning 1) 5))
             (goto-char (match-end 0)))
           (make-string (current-column) ?\ )))
-       ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)]  ?\\)?")
+    ;; Ordered or unordered list
+       ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)]  ?\\)")
         (save-excursion
           (goto-char (match-end 0))
           (make-string (current-column) ?\ )))
-       (t nil)))
+    ;; Other text
+    ((looking-at org-adaptive-fill-regexp-backup)
+     (match-string-no-properties 0))))
 
 ;;; Other stuff.
 
@@ -16425,7 +18855,7 @@ This looks for a line like
 
 #+BIBLIOGRAPHY: foo plain option:-d
 
-and derives from it that foo.bib is the bbliography file relevant
+and derives from it that foo.bib is the bibliography file relevant
 for this document.  It then installs the necessary environment for RefTeX
 to work in this buffer and calls `reftex-citation'  to insert a citation
 into the buffer.
@@ -16471,8 +18901,8 @@ beyond the end of the headline."
       (if (bobp)
          nil
        (backward-char 1)
-       (if (org-invisible-p)
-           (while (and (not (bobp)) (org-invisible-p))
+       (if (org-truely-invisible-p)
+           (while (and (not (bobp)) (org-truely-invisible-p))
              (backward-char 1)
              (beginning-of-line 1))
          (forward-char 1))))
@@ -16520,7 +18950,7 @@ beyond the end of the headline."
               (t 'end-of-line)))
       (let ((pos (point)))
        (beginning-of-line 1)
-       (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
+       (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
            (if (eq special t)
                (if (or (< pos (match-beginning 1))
                        (= pos (match-end 0)))
@@ -16566,8 +18996,13 @@ depending on context."
    ((or (not org-special-ctrl-k)
        (bolp)
        (not (org-on-heading-p)))
+    (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
+            org-ctrl-k-protect-subtree)
+       (if (or (eq org-ctrl-k-protect-subtree 'error)
+               (not (y-or-n-p "Kill hidden subtree along with headline? ")))
+           (error "C-k aborted - would kill hidden subtree")))
     (call-interactively 'kill-line))
-   ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
+   ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
     (kill-region (point) (match-beginning 1))
     (org-set-tags nil t))
    (t (kill-region (point) (point-at-eol)))))
@@ -16593,7 +19028,8 @@ org-yank-adjusted-subtrees
     *visible* surrounding headings.
 
 Any prefix to this command will cause `yank' to be called directly with
-no special treatment.  In particular, a simple `C-u' prefix will just
+no special treatment.  In particular, a simple \\[universal-argument] prefix \
+will just
 plainly yank the text as it is.
 
 \[1] The test checks if the first non-white line is a heading
@@ -16683,6 +19119,17 @@ interactive command with similar behavior."
       (outline-invisible-p)
     (get-char-property (point) 'invisible)))
 
+(defun org-truely-invisible-p ()
+  "Check if point is at a character currently not visible.
+This version does not only check the character property, but also
+`visible-mode'."
+  ;; Early versions of noutline don't have `outline-invisible-p'.
+  (if (org-bound-and-true-p visible-mode)
+      nil
+    (if (fboundp 'outline-invisible-p)
+       (outline-invisible-p)
+      (get-char-property (point) 'invisible))))
+
 (defun org-invisible-p2 ()
   "Check if point is at a character currently not visible."
   (save-excursion
@@ -16699,13 +19146,32 @@ interactive command with similar behavior."
     (error (error "Before first headline at position %d in buffer %s"
                  (point) (current-buffer)))))
 
+(defun org-beginning-of-defun ()
+  "Go to the beginning of the subtree, i.e. back to the heading."
+  (org-back-to-heading))
+(defun org-end-of-defun ()
+  "Go to the end of the subtree."
+  (org-end-of-subtree nil t))
+
 (defun org-before-first-heading-p ()
   "Before first heading?"
   (save-excursion
     (null (re-search-backward "^\\*+ " nil t))))
 
-(defalias 'org-on-heading-p 'outline-on-heading-p)
-(defalias 'org-at-heading-p 'outline-on-heading-p)
+(defun org-on-heading-p (&optional ignored)
+  (outline-on-heading-p t))
+(defun org-at-heading-p (&optional ignored)
+  (outline-on-heading-p t))
+
+(defun org-point-at-end-of-empty-headline ()
+  "If point is at the end of an empty headline, return t, else nil.
+If the heading only contains a TODO keyword, it is still still considered
+empty."
+  (and (looking-at "[ \t]*$")
+       (save-excursion
+         (beginning-of-line 1)
+         (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
+                            "\\)?[ \t]*$")))))
 (defun org-at-heading-or-item-p ()
   (or (org-on-heading-p) (org-at-item-p)))
 
@@ -16780,6 +19246,18 @@ move point."
     (while (org-goto-sibling 'previous)
       (org-flag-heading nil))))
 
+(defun org-goto-first-child ()
+  "Goto the first child, even if it is invisible.
+Return t when a child was found. Otherwise don't move point and
+return nil."
+  (let (level (pos (point)) (re (concat "^" outline-regexp)))
+    (when (condition-case nil (org-back-to-heading t) (error nil))
+      (setq level (outline-level))
+      (forward-char 1)
+      (if (and (re-search-forward re nil t) (> (outline-level) level))
+         (progn (goto-char (match-beginning 0)) t)
+       (goto-char pos) nil))))
+
 (defun org-show-hidden-entry ()
   "Show an entry where even the heading is hidden."
   (save-excursion
@@ -16866,12 +19344,14 @@ If there is no such heading, return nil."
   (if (eq major-mode 'org-mode)
       (progn
        (org-end-of-subtree nil t)
-       (backward-char 1))
+       (unless (eobp) (backward-char 1)))
     ad-do-it))
 
 (defun org-forward-same-level (arg &optional invisible-ok)
   "Move forward to the arg'th subheading at same level as this one.
-Stop at the first and last subheadings of a superior heading."
+Stop at the first and last subheadings of a superior heading.
+Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
+it wil also look at invisible ones."
   (interactive "p")
   (org-back-to-heading invisible-ok)
   (org-on-heading-p)
@@ -16884,7 +19364,7 @@ Stop at the first and last subheadings of a superior heading."
                  (setq l (- (match-end 0) (match-beginning 0) 1))
                  (= l level)
                  (not invisible-ok)
-                 (org-invisible-p))
+                 (progn (backward-char 1) (org-invisible-p)))
        (if (< l level) (setq arg 1)))
       (setq arg (1- arg)))
     (beginning-of-line 1)))
@@ -17022,19 +19502,20 @@ Show the heading too, if it is currently invisible."
 if no description is present"
   (save-match-data
     (if (string-match org-bracket-link-analytic-regexp link)
-       (replace-match (or (match-string 5 link)
-                          (concat (match-string 1 link)
-                                  (match-string 3 link)))
-                      nil nil link)
+           (replace-match (if (match-end 5)
+                              (match-string 5 link)
+                            (concat (match-string 1 link)
+                                    (match-string 3 link)))
+                          nil t link)
       link)))
 
 ;; Speedbar support
 
-(defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
+(defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
   "Overlay marking the agenda restriction line in speedbar.")
-(org-overlay-put org-speedbar-restriction-lock-overlay
+(overlay-put org-speedbar-restriction-lock-overlay
                 'face 'org-agenda-restriction-lock)
-(org-overlay-put org-speedbar-restriction-lock-overlay
+(overlay-put org-speedbar-restriction-lock-overlay
                 'help-echo "Agendas are currently limited to this item.")
 (org-detach-overlay org-speedbar-restriction-lock-overlay)
 
@@ -17048,11 +19529,9 @@ To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
      ((setq p (text-property-any (point-at-bol) (point-at-eol)
                                 'org-imenu t))
       (setq m (get-text-property p 'org-imenu-marker))
-      (save-excursion
-       (save-restriction
-         (set-buffer (marker-buffer m))
-         (goto-char m)
-         (org-agenda-set-restriction-lock 'subtree))))
+      (with-current-buffer (marker-buffer m)
+       (goto-char m)
+       (org-agenda-set-restriction-lock 'subtree)))
      ((setq p (text-property-any (point-at-bol) (point-at-eol)
                                 'speedbar-function 'speedbar-find-file))
       (setq tp (previous-single-property-change
@@ -17062,17 +19541,15 @@ To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
            dir (speedbar-line-directory)
            txt (buffer-substring-no-properties (or tp (point-min))
                                                (or np (point-max))))
-      (save-excursion
-       (save-restriction
-         (set-buffer (find-file-noselect
-                      (let ((default-directory dir))
-                        (expand-file-name txt))))
-         (unless (org-mode-p)
-           (error "Cannot restrict to non-Org-mode file"))
-         (org-agenda-set-restriction-lock 'file))))
+      (with-current-buffer (find-file-noselect
+                           (let ((default-directory dir))
+                             (expand-file-name txt)))
+       (unless (org-mode-p)
+         (error "Cannot restrict to non-Org-mode file"))
+       (org-agenda-set-restriction-lock 'file)))
      (t (error "Don't know how to restrict Org-mode's agenda")))
-    (org-move-overlay org-speedbar-restriction-lock-overlay
-                     (point-at-bol) (point-at-eol))
+    (move-overlay org-speedbar-restriction-lock-overlay
+                 (point-at-bol) (point-at-eol))
     (setq current-prefix-arg nil)
     (org-agenda-maybe-redo)))
 
@@ -17086,14 +19563,13 @@ To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
      (add-hook 'speedbar-visiting-tag-hook
               (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
 
-
 ;;; Fixes and Hacks for problems with 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."
-  (and (not (get-text-property (point) 'keymap))
-       (not (get-text-property (point) 'org-no-flyspell))))
+  (and (not (get-text-property (max (1- (point)) (point-min)) 'keymap))
+       (not (get-text-property (max (1- (point)) (point-min)) 'org-no-flyspell))))
 
 (defun org-remove-flyspell-overlays-in (beg end)
   "Remove flyspell overlays in region."
@@ -17102,7 +19578,7 @@ To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
        (flyspell-delete-region-overlays beg end))
   (add-text-properties beg end '(org-no-flyspell t)))
 
-;; Make `bookmark-jump' show the jump location if it was hidden.
+;; Make `bookmark-jump' shows the jump location if it was hidden.
 (eval-after-load "bookmark"
   '(if (boundp 'bookmark-after-jump-hook)
        ;; We can use the hook
@@ -17112,12 +19588,19 @@ To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
        "Make the position visible."
        (org-bookmark-jump-unhide))))
 
-;; Make sure saveplace show the location if it was hidden
+;; Make sure saveplace shows the location if it was hidden
 (eval-after-load "saveplace"
   '(defadvice save-place-find-file-hook (after org-make-visible activate)
      "Make the position visible."
      (org-bookmark-jump-unhide)))
 
+;; Make sure ecb shows the location if it was hidden
+(eval-after-load "ecb"
+  '(defadvice ecb-method-clicked (after esf/org-show-context activate)
+     "Make hierarchy visible when jumping into location from ECB tree buffer."
+     (if (eq major-mode 'org-mode)
+        (org-show-context))))
+
 (defun org-bookmark-jump-unhide ()
   "Unhide the current position, to show the bookmark location."
   (and (org-mode-p)