]> code.delx.au - gnu-emacs/blobdiff - lisp/org/org-exp.el
Merge from emacs-23
[gnu-emacs] / lisp / org / org-exp.el
index 11452045384be6bf462af940ebdad13b1408e0a9..a334c45a7f79a0d60f091b4954e997762f7e5e03 100644 (file)
@@ -6,7 +6,7 @@
 ;; Author: Carsten Dominik <carsten at orgmode dot org>
 ;; Keywords: outlines, hypermedia, calendar, wp
 ;; Homepage: http://orgmode.org
-;; Version: 6.33x
+;; Version: 7.4
 ;;
 ;; This file is part of GNU Emacs.
 ;;
 ;;
 ;;; Commentary:
 
+;;; Code:
+
 (require 'org)
 (require 'org-macs)
 (require 'org-agenda)
 (require 'org-exp-blocks)
+(require 'ob-exp)
 (require 'org-src)
+
 (eval-when-compile
   (require 'cl))
 
@@ -42,6 +46,8 @@
 (declare-function org-export-htmlize-region-for-paste "org-html" (beg end))
 (declare-function htmlize-buffer "ext:htmlize" (&optional buffer))
 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
+(declare-function org-table-cookie-line-p "org-table" (line))
+(declare-function org-table-colgroup-line-p "org-table" (line))
 (autoload 'org-export-generic "org-export-generic" "Export using the generic exporter" t)
 (defgroup org-export nil
   "Options for exporting org-listings."
@@ -54,7 +60,7 @@
   :group 'org-export)
 
 (defcustom org-export-allow-BIND 'confirm
-  "Non-nil means, allow #+BIND to define local variable values for export.
+  "Non-nil means allow #+BIND to define local variable values for export.
 This is a potential security risk, which is why the user must confirm the
 use of these lines."
   :group 'org-export-general
@@ -67,7 +73,7 @@ use of these lines."
 (defvar org-export-publishing-directory nil)
 
 (defcustom org-export-show-temporary-export-buffer t
-  "Non-nil means, show buffer after exporting to temp buffer.
+  "Non-nil means show buffer after exporting to temp buffer.
 When Org exports to a file, the buffer visiting that file is ever
 shown, but remains buried.  However, when exporting to a temporary
 buffer, that buffer is popped up in a second window.  When this variable
@@ -76,7 +82,14 @@ is nil, the buffer remains buried also in these cases."
   :type 'boolean)
 
 (defcustom org-export-copy-to-kill-ring t
-  "Non-nil means, exported stuff will also be pushed onto the kill ring."
+  "Non-nil means exported stuff will also be pushed onto the kill ring."
+  :group 'org-export-general
+  :type 'boolean)
+
+(defcustom org-export-kill-product-buffer-when-displayed nil
+  "Non-nil means kill the product buffer if it is displayed immediately.
+This applied to the commands `org-export-html-and-open' and
+`org-export-as-pdf-and-open'."
   :group 'org-export-general
   :type 'boolean)
 
@@ -86,9 +99,10 @@ This works by starting up a separate Emacs process visiting the same file
 and doing the export from there.
 Not all export commands are affected by this - only the ones which
 actually write to a file, and that do not depend on the buffer state.
-
+\\<org-mode-map>
 If this option is nil, you can still get background export by calling
-`org-export' with a double prefix arg: `C-u C-u C-c C-e'.
+`org-export' with a double prefix arg: \
+\\[universal-argument] \\[universal-argument] \\[org-export].
 
 If this option is t, the double prefix can be used to exceptionally
 force an export command into the current process."
@@ -114,7 +128,7 @@ This is without condition, so even subtrees inside that carry one of the
 
 ;; FIXME: rename, this is a general variable
 (defcustom org-export-html-expand t
-  "Non-nil means, for HTML export, treat @<...> as HTML tag.
+  "Non-nil means for HTML export, treat @<...> as HTML tag.
 When nil, these tags will be exported as plain text and therefore
 not be interpreted by a browser.
 
@@ -124,7 +138,7 @@ This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
   :type 'boolean)
 
 (defcustom org-export-with-special-strings t
-  "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
+  "Non-nil means interpret \"\-\", \"--\" and \"---\" for export.
 When this option is turned on, these strings will be exported as:
 
   Org   HTML       LaTeX
@@ -167,7 +181,7 @@ This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
     ("no" "Forfatter"  "Dato"  "Innhold" "Fotnoter")
     ("nb" "Forfatter"  "Dato"  "Innhold" "Fotnoter")  ;; nb = Norsk (bokm.l)
     ("nn" "Forfattar"  "Dato"  "Innhald" "Fotnotar")  ;; nn = Norsk (nynorsk)
-    ("pl" "Autor"      "Data" "Spis tre&sacute;ci"  "Przypis")
+    ("pl" "Autor"      "Data" "Spis tre&#x015b;ci"  "Przypis")
     ("sv" "F&ouml;rfattare" "Datum" "Inneh&aring;ll" "Fotnoter"))
   "Terms used in export text, translated to different languages.
 Use the variable `org-export-default-language' to set the language,
@@ -198,7 +212,7 @@ This is best set with the #+KEYWORDS line in a file, it does not make
 sense to set this globally.")
 
 (defcustom org-export-skip-text-before-1st-heading nil
-  "Non-nil means, skip all text before the first headline when exporting.
+  "Non-nil means skip all text before the first headline when exporting.
 When nil, that text is exported as well."
   :group 'org-export-general
   :type 'boolean)
@@ -214,7 +228,7 @@ This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
   :type 'integer)
 
 (defcustom org-export-with-section-numbers t
-  "Non-nil means, add section numbers to headlines when exporting.
+  "Non-nil means add section numbers to headlines when exporting.
 
 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
   :group 'org-export-general
@@ -224,7 +238,7 @@ This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
   "Format of section numbers for export.
 The variable has two components.
 1. A list of lists, each indicating a counter type and a separator.
-   The counter type can be any of \"1\", \"A\", \"a\", \"I\", or \"a\".
+   The counter type can be any of \"1\", \"A\", \"a\", \"I\", or \"i\".
    It causes causes numeric, alphabetic, or roman counters, respectively.
    The separator is only used if another counter for a subsection is being
    added.
@@ -241,7 +255,7 @@ The variable has two components.
          (string :tag "Terminator")))
 
 (defcustom org-export-with-toc t
-  "Non-nil means, create a table of contents in exported files.
+  "Non-nil means create a table of contents in exported files.
 The TOC contains headlines with levels up to`org-export-headline-levels'.
 When an integer, include levels up to N in the toc, this may then be
 different from `org-export-headline-levels', but it will not be allowed
@@ -263,24 +277,24 @@ or \"toc:3\"."
          (integer :tag "TOC to level")))
 
 (defcustom org-export-mark-todo-in-toc nil
-  "Non-nil means, mark TOC lines that contain any open TODO items."
+  "Non-nil means mark TOC lines that contain any open TODO items."
   :group 'org-export-general
   :type 'boolean)
 
 (defcustom org-export-with-todo-keywords t
-  "Non-nil means, include TODO keywords in export.
+  "Non-nil means include TODO keywords in export.
 When nil, remove all these keywords from the export."
   :group 'org-export-general
   :type 'boolean)
 
 (defcustom org-export-with-priority nil
-  "Non-nil means, include priority cookies in export.
+  "Non-nil means include priority cookies in export.
 When nil, remove priority cookies for export."
   :group 'org-export-general
   :type 'boolean)
 
 (defcustom org-export-preserve-breaks nil
-  "Non-nil means, preserve all line breaks when exporting.
+  "Non-nil means preserve all line breaks when exporting.
 Normally, in HTML output paragraphs will be reformatted.  In ASCII
 export, line breaks will always be preserved, regardless of this variable.
 
@@ -302,21 +316,29 @@ headline  Only export the headline, but skip the tree below it."
          (const :tag "entirely" t)))
 
 (defcustom org-export-author-info t
-  "Non-nil means, insert author name and email into the exported file.
+  "Non-nil means insert author name and email into the exported file.
 
 This option can also be set with the +OPTIONS line,
-e.g. \"author-info:nil\"."
+e.g. \"author:nil\"."
+  :group 'org-export-general
+  :type 'boolean)
+
+(defcustom org-export-email-info nil
+  "Non-nil means insert author name and email into the exported file.
+
+This option can also be set with the +OPTIONS line,
+e.g. \"email:t\"."
   :group 'org-export-general
   :type 'boolean)
 
 (defcustom org-export-creator-info t
-  "Non-nil means, the postamble should contain a creator sentence.
+  "Non-nil means the postamble should contain a creator sentence.
 This sentence is \"HTML generated by org-mode XX in emacs XXX\"."
   :group 'org-export-general
   :type 'boolean)
 
 (defcustom org-export-time-stamp-file t
-  "Non-nil means, insert a time stamp into the exported file.
+  "Non-nil means insert a time stamp into the exported file.
 The time stamp shows when the file was created.
 
 This option can also be set with the +OPTIONS line,
@@ -347,7 +369,7 @@ This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
          (const :tag "On" t)))
 
 (defcustom org-export-with-drawers nil
-  "Non-nil means, export with drawers like the property drawer.
+  "Non-nil means export with drawers like the property drawer.
 When t, all drawers are exported.  This may also be a list of
 drawer names to export."
   :group 'org-export-general
@@ -357,9 +379,19 @@ drawer names to export."
          (repeat :tag "Selected drawers"
                  (string :tag "Drawer name"))))
 
+(defvar org-export-first-hook nil
+  "Hook called as the first thing in each exporter.
+Point will be still in the original buffer.
+Good for general initialization")
+
 (defvar org-export-preprocess-hook nil
   "Hook for preprocessing an export buffer.
-Pretty much the first thing when exporting is running this hook.")
+Pretty much the first thing when exporting is running this hook.
+Point will be in a temporary buffer that contains a copy of
+the original buffer, or of the section that is being export.
+All the other hooks in the org-export-preprocess... category
+also work in that temporary buffer, already modified by various
+stages of the processing.")
 
 (defvar org-export-preprocess-after-include-files-hook nil
   "Hook for preprocessing an export buffer.
@@ -371,11 +403,28 @@ This is run after selection of trees to be exported has happened.
 This selection includes tags-based selection, as well as removal
 of commented and archived trees.")
 
+(defvar org-export-preprocess-after-headline-targets-hook nil
+  "Hook for preprocessing export buffer.
+This is run just after the headline targets have been defined and
+the target-alist has been set up.")
+
+(defvar org-export-preprocess-before-selecting-backend-code-hook nil
+  "Hook for preprocessing an export buffer.
+This is run just before backend-specific blocks get selected.")
+
 (defvar org-export-preprocess-after-blockquote-hook nil
   "Hook for preprocessing an export buffer.
 This is run after blockquote/quote/verse/center have been marked
 with cookies.")
 
+(defvar org-export-preprocess-after-radio-targets-hook nil
+  "Hook for preprocessing an export buffer.
+This is run after radio target processing.")
+
+(defvar org-export-preprocess-before-normalizing-links-hook nil
+  "Hook for preprocessing an export buffer.
+This hook is run before links are normalized.")
+
 (defvar org-export-preprocess-before-backend-specifics-hook nil
   "Hook run before backend-specific functions are called during preprocessing.")
 
@@ -390,7 +439,7 @@ returning the buffer string to the backend.")
   :group 'org-export)
 
 (defcustom org-export-with-emphasize t
-  "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
+  "Non-nil means interpret *word*, /word/, and _word_ as emphasized text.
 If the export target supports emphasizing text, the word will be
 typeset in bold, italic, or underlined, respectively.  Works only for
 single words, but you can say: I *really* *mean* *this*.
@@ -408,41 +457,13 @@ This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
   :group 'org-export-translation
   :type 'boolean)
 
-(defcustom org-export-with-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-export-translation
-  :type '(choice
-         (const :tag "Always interpret" t)
-         (const :tag "Only with braces" {})
-         (const :tag "Never interpret" nil)))
-
 (defcustom org-export-with-TeX-macros t
-  "Non-nil means, interpret simple TeX-like macros when exporting.
+  "Non-nil means interpret simple TeX-like macros when exporting.
 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
 Not only real TeX macros will work here, but the standard HTML entities
 for math can be used as macro names as well.  For a list of supported
-names in HTML export, see the constant `org-html-entities'.
+names in HTML export, see the constant `org-entities' and the user option
+`org-entities-user'.
 Not all export backends support this.
 
 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
@@ -450,23 +471,37 @@ This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
   :group 'org-export-latex
   :type 'boolean)
 
-(defcustom org-export-with-LaTeX-fragments nil
-  "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
-When set, the exporter will find LaTeX environments if the \\begin line is
-the first non-white thing on a line.  It will also find the math delimiters
-like $a=b$ and \\( a=b \\) for inline math,  $$a=b$$ and \\[ a=b \\] for
-display math.
+(defcustom org-export-with-LaTeX-fragments t
+  "Non-nil means process LaTeX math fragments for HTML display.
+When set, the exporter will find and process LaTeX environments if the
+\\begin line is the first non-white thing on a line.  It will also find
+and process  the math delimiters like $a=b$ and \\( a=b \\) for inline math,
+$$a=b$$ and \\[ a=b \\] for display math.
+
+This option can also be set with the +OPTIONS line, e.g. \"LaTeX:mathjax\".
+
+Allowed values are:
 
-This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\".
+nil        Don't do anything.
+verbatim   Keep eveything in verbatim
+dvipng     Process the LaTeX fragments to images.
+           This will also include processing of non-math environments.
+t          Do MathJax preprocessing if there is at least on math snippet,
+           and arrange for MathJax.js to be loaded.
 
 The default is nil, because this option needs the `dvipng' program which
 is not available on all systems."
   :group 'org-export-translation
   :group 'org-export-latex
-  :type 'boolean)
+  :type '(choice
+         (const :tag "Do not process math in any way" nil)
+         (const :tag "Obsolete, use dvipng setting" t)
+         (const :tag "Use dvipng to make images" dvipng)
+         (const :tag "Use MathJax to display math" mathjax)
+         (const :tag "Leave math verbatim" verbatim)))
 
 (defcustom org-export-with-fixed-width t
-  "Non-nil means, lines starting with \":\" will be in fixed width font.
+  "Non-nil means lines starting with \":\" will be in fixed width font.
 This can be used to have pre-formatted text, fragments of code etc.  For
 example:
   : ;; Some Lisp examples
@@ -479,12 +514,6 @@ This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
   :group 'org-export-translation
   :type 'boolean)
 
-(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)
-
 (defgroup org-export-tables nil
   "Options for exporting tables in Org-mode."
   :tag "Org Export Tables"
@@ -505,7 +534,7 @@ This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
   :type 'boolean)
 
 (defcustom org-export-highlight-first-table-line t
-  "Non-nil means, highlight the first table line.
+  "Non-nil means highlight the first table line.
 In HTML export, this means use <th> instead of <td>.
 In tables created with table.el, this applies to the first table line.
 In Org-mode tables, all lines before the first horizontal separator
@@ -523,13 +552,14 @@ the values of constants may be useful to have."
   :type 'boolean)
 
 (defcustom org-export-prefer-native-exporter-for-tables nil
-  "Non-nil means, always export tables created with table.el natively.
-Natively means, use the HTML code generator in table.el.
+  "Non-nil means always export tables created with table.el natively.
+Natively means use the HTML code generator in table.el.
 When nil, Org-mode's own HTML generator is used when possible (i.e. if
 the table does not use row- or column-spanning).  This has the
 advantage, that the automatic HTML conversions for math symbols and
 sub/superscripts can be applied.  Org-mode's HTML generator is also
-much faster."
+much faster.  The LaTeX exporter always use the native exporter for
+table.el tables."
   :group 'org-export-tables
   :type 'boolean)
 
@@ -581,6 +611,7 @@ much faster."
     (:fixed-width            ":"         org-export-with-fixed-width)
     (:timestamps             "<"         org-export-with-timestamps)
     (:author-info            "author"    org-export-author-info)
+    (:email-info             "email"     org-export-email-info)
     (:creator-info           "creator"   org-export-creator-info)
     (:time-stamp-file        "timestamp" org-export-time-stamp-file)
     (:tables                 "|"         org-export-with-tables)
@@ -658,12 +689,14 @@ modified) list.")
       (let ((re (org-make-options-regexp
                 (append
                  '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"
+                   "MATHJAX"
                    "LINK_UP" "LINK_HOME" "SETUPFILE" "STYLE"
                    "LATEX_HEADER" "LATEX_CLASS"
                    "EXPORT_SELECT_TAGS" "EXPORT_EXCLUDE_TAGS"
-                   "KEYWORDS" "DESCRIPTION" "MACRO" "BIND")
+                   "KEYWORDS" "DESCRIPTION" "MACRO" "BIND" "XSLT")
                  (mapcar 'car org-export-inbuffer-options-extra))))
-           p key val text options a pr style
+           (case-fold-search t)
+           p key val text options mathjax a pr style
            latex-header latex-class macros letbind
            ext-setup-or-nil setup-contents (start 0))
        (while (or (and ext-setup-or-nil
@@ -695,8 +728,12 @@ modified) list.")
            (setq text (if text (concat text "\n" val) val)))
           ((string-equal key "OPTIONS")
            (setq options (concat val " " options)))
+          ((string-equal key "MATHJAX")
+           (setq mathjax (concat val " " mathjax)))
           ((string-equal key "BIND")
            (push (read (concat "(" val ")")) letbind))
+          ((string-equal key "XSLT")
+           (setq p (plist-put p :xslt val)))
           ((string-equal key "LINK_UP")
            (setq p (plist-put p :link-up val)))
           ((string-equal key "LINK_HOME")
@@ -729,9 +766,12 @@ modified) list.")
          (setq p (plist-put p :latex-class latex-class)))
        (when options
          (setq p (org-export-add-options-to-plist p options)))
+       (when mathjax
+         (setq p (plist-put p :mathjax mathjax)))
        ;; Add macro definitions
        (setq p (plist-put p :macro-date "(eval (format-time-string \"$1\"))"))
        (setq p (plist-put p :macro-time "(eval (format-time-string \"$1\"))"))
+       (setq p (plist-put p :macro-property "(eval (org-entry-get nil \"$1\" 'selective))"))
        (setq p (plist-put
                 p :macro-modification-time
                 (and (buffer-file-name)
@@ -772,9 +812,10 @@ security risks."
 
 (defun org-install-letbind ()
   "Install the values from #+BIND lines as local variables."
-  (let ((letbind (plist-get org-export-opt-plist :let-bind)))
-    (while letbind
-      (org-set-local (caar letbind) (nth 1 (pop letbind))))))
+  (let ((letbind (plist-get org-export-opt-plist :let-bind))
+       pair)
+    (while (setq pair (pop letbind))
+      (org-set-local (car pair) (nth 1 pair)))))
 
 (defun org-export-add-options-to-plist (p options)
   "Parse an OPTIONS line and set values in the property list P."
@@ -831,33 +872,35 @@ in the background.  This will be done only for commands that write
 to a file.  For details see the docstring of `org-export-run-in-background'.
 
 The prefix argument ARG will be passed to the exporter.  However, if
-ARG is a double universal prefix `C-u C-u', that means to inverse the
+ARG is a double universal prefix \\[universal-argument] \\[universal-argument], \
+that means to inverse the
 value of `org-export-run-in-background'."
   (interactive "P")
   (let* ((bg (org-xor (equal arg '(16)) org-export-run-in-background))
+        subtree-p
         (help "[t]   insert the export option template
 \[v]   limit export to visible part of outline tree
+\[1]   only export the current subtree
+\[SPC] publish enclosing subtree (with LaTeX_CLASS or EXPORT_FILE_NAME prop)
 
-\[a] export as ASCII   [A] to temporary buffer
+\[a/n/u] export as ASCII/Latin-1/UTF-8         [A/N/U] to temporary buffer
 
-\[h] export as HTML    [H] to temporary buffer   [R] export region
+\[h] export as HTML      [H] to temporary buffer   [R] export region
 \[b] export as HTML and open in browser
 
-\[l] export as LaTeX   [L] to temporary buffer
-\[p] export as LaTeX and process to PDF
-\[d] export as LaTeX, process to PDF, and open the resulting PDF document
+\[l] export as LaTeX     [L] to temporary buffer
+\[p] export as LaTeX and process to PDF            [d] ... and open PDF file
 
-\[D] export as DocBook
-\[V] export as DocBook, process to PDF, and open the resulting PDF document
+\[D] export as DocBook   [V] export as DocBook, process to PDF, and open
 
-\[m] export as Freemind mind map
+\[j] export as TaskJuggler                         [J] ... and open
 
+\[m] export as Freemind mind map
 \[x] export as XOXO
 \[g] export using Wes Hardaker's generic exporter
 
 \[i] export current file as iCalendar file
-\[I] export all agenda files as iCalendar files
-\[c] export agenda files into combined iCalendar file
+\[I] export all agenda files as iCalendar files   [c] ...as one combined file
 
 \[F] publish current file          [P] publish current project
 \[X] publish a project...          [E] publish every projects")
@@ -866,6 +909,10 @@ value of `org-export-run-in-background'."
            (?v org-export-visible nil)
            (?a org-export-as-ascii t)
            (?A org-export-as-ascii-to-buffer t)
+           (?n org-export-as-latin1 t)
+           (?N org-export-as-latin1-to-buffer t)
+           (?u org-export-as-utf8 t)
+           (?U org-export-as-utf8-to-buffer t)
            (?h org-export-as-html t)
            (?b org-export-as-html-and-open t)
            (?H org-export-as-html-to-buffer nil)
@@ -874,6 +921,8 @@ value of `org-export-run-in-background'."
            (?g org-export-generic t)
            (?D org-export-as-docbook t)
            (?V org-export-as-docbook-pdf-and-open t)
+           (?j org-export-as-taskjuggler t)
+           (?J org-export-as-taskjuggler-and-open t)
            (?m org-export-as-freemind t)
            (?l org-export-as-latex t)
            (?p org-export-as-pdf t)
@@ -886,7 +935,8 @@ value of `org-export-run-in-background'."
            (?P org-publish-current-project t)
            (?X org-publish t)
            (?E org-publish-all t)))
-        r1 r2 ass)
+        r1 r2 ass
+        (cpos (point)) (cbuf (current-buffer)) bpos)
     (save-excursion
       (save-window-excursion
        (delete-other-windows)
@@ -895,7 +945,25 @@ value of `org-export-run-in-background'."
        (org-fit-window-to-buffer (get-buffer-window
                                   "*Org Export/Publishing Help*"))
        (message "Select command: ")
-       (setq r1 (read-char-exclusive))))
+       (setq r1 (read-char-exclusive))
+       (when (eq r1 ?1)
+         (setq subtree-p t)
+         (message "Select command (for subtree): ")
+         (setq r1 (read-char-exclusive)))
+       (when (eq r1 ?\ )
+         (let ((case-fold-search t))
+           (if (re-search-backward
+                "^[ \t]+\\(:latex_class:\\|:export_title:\\)[ \t]+\\S-"
+                nil t)
+               (progn
+                 (org-back-to-heading t)
+                 (setq subtree-p t)
+                 (setq bpos (point))
+                 (message "Select command (for subtree): ")
+                 (setq r1 (read-char-exclusive)))
+             (error "No enclosing node with LaTeX_CLASS or EXPORT_FILE_NAME")
+             )))))
+    (and bpos (goto-char bpos))
     (setq r2 (if (< r1 27) (+ r1 96) r1))
     (unless (setq ass (assq r2 cmds))
       (error "No command associated with key %c" r1))
@@ -916,322 +984,30 @@ value of `org-export-run-in-background'."
          (set-process-sentinel p 'org-export-process-sentinel)
          (message "Background process \"%s\": started" p))
       ;; background processing not requested, or not possible
-      (call-interactively (nth 1 ass)))))
+      (if subtree-p (progn (org-mark-subtree) (activate-mark)))
+      (call-interactively (nth 1 ass))
+      (when (and bpos (get-buffer-window cbuf))
+       (let ((cw (selected-window)))
+         (select-window (get-buffer-window cbuf))
+         (goto-char cpos)
+         (deactivate-mark)
+         (select-window cw))))))
 
 (defun org-export-process-sentinel (process status)
   (if (string-match "\n+\\'" status)
       (setq status (substring status 0 -1)))
   (message "Background process \"%s\": %s" process status))
 
-(defconst org-html-entities
-  '(("nbsp")
-    ("iexcl")
-    ("cent")
-    ("pound")
-    ("curren")
-    ("yen")
-    ("brvbar")
-    ("vert" . "&#124;")
-    ("sect")
-    ("uml")
-    ("copy")
-    ("ordf")
-    ("laquo")
-    ("not")
-    ("shy")
-    ("reg")
-    ("macr")
-    ("deg")
-    ("pm" . "&plusmn;")
-    ("plusmn")
-    ("sup2")
-    ("sup3")
-    ("acute")
-    ("micro")
-    ("para")
-    ("middot")
-    ("odot"."o")
-    ("star"."*")
-    ("cedil")
-    ("sup1")
-    ("ordm")
-    ("raquo")
-    ("frac14")
-    ("frac12")
-    ("frac34")
-    ("iquest")
-    ("Agrave")
-    ("Aacute")
-    ("Acirc")
-    ("Atilde")
-    ("Auml")
-    ("Aring") ("AA"."&Aring;")
-    ("AElig")
-    ("Ccedil")
-    ("Egrave")
-    ("Eacute")
-    ("Ecirc")
-    ("Euml")
-    ("Igrave")
-    ("Iacute")
-    ("Icirc")
-    ("Iuml")
-    ("ETH")
-    ("Ntilde")
-    ("Ograve")
-    ("Oacute")
-    ("Ocirc")
-    ("Otilde")
-    ("Ouml")
-    ("times")
-    ("Oslash")
-    ("Ugrave")
-    ("Uacute")
-    ("Ucirc")
-    ("Uuml")
-    ("Yacute")
-    ("THORN")
-    ("szlig")
-    ("agrave")
-    ("aacute")
-    ("acirc")
-    ("atilde")
-    ("auml")
-    ("aring")
-    ("aelig")
-    ("ccedil")
-    ("egrave")
-    ("eacute")
-    ("ecirc")
-    ("euml")
-    ("igrave")
-    ("iacute")
-    ("icirc")
-    ("iuml")
-    ("eth")
-    ("ntilde")
-    ("ograve")
-    ("oacute")
-    ("ocirc")
-    ("otilde")
-    ("ouml")
-    ("divide")
-    ("oslash")
-    ("ugrave")
-    ("uacute")
-    ("ucirc")
-    ("uuml")
-    ("yacute")
-    ("thorn")
-    ("yuml")
-    ("fnof")
-    ("Alpha")
-    ("Beta")
-    ("Gamma")
-    ("Delta")
-    ("Epsilon")
-    ("Zeta")
-    ("Eta")
-    ("Theta")
-    ("Iota")
-    ("Kappa")
-    ("Lambda")
-    ("Mu")
-    ("Nu")
-    ("Xi")
-    ("Omicron")
-    ("Pi")
-    ("Rho")
-    ("Sigma")
-    ("Tau")
-    ("Upsilon")
-    ("Phi")
-    ("Chi")
-    ("Psi")
-    ("Omega")
-    ("alpha")
-    ("beta")
-    ("gamma")
-    ("delta")
-    ("epsilon")
-    ("varepsilon"."&epsilon;")
-    ("zeta")
-    ("eta")
-    ("theta")
-    ("iota")
-    ("kappa")
-    ("lambda")
-    ("mu")
-    ("nu")
-    ("xi")
-    ("omicron")
-    ("pi")
-    ("rho")
-    ("sigmaf") ("varsigma"."&sigmaf;")
-    ("sigma")
-    ("tau")
-    ("upsilon")
-    ("phi")
-    ("chi")
-    ("psi")
-    ("omega")
-    ("thetasym") ("vartheta"."&thetasym;")
-    ("upsih")
-    ("piv")
-    ("bull") ("bullet"."&bull;")
-    ("hellip") ("dots"."&hellip;")
-    ("prime")
-    ("Prime")
-    ("oline")
-    ("frasl")
-    ("weierp")
-    ("image")
-    ("real")
-    ("trade")
-    ("alefsym")
-    ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
-    ("uarr") ("uparrow"."&uarr;")
-    ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
-    ("darr")("downarrow"."&darr;")
-    ("harr") ("leftrightarrow"."&harr;")
-    ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
-    ("lArr") ("Leftarrow"."&lArr;")
-    ("uArr") ("Uparrow"."&uArr;")
-    ("rArr") ("Rightarrow"."&rArr;")
-    ("dArr") ("Downarrow"."&dArr;")
-    ("hArr") ("Leftrightarrow"."&hArr;")
-    ("forall")
-    ("part") ("partial"."&part;")
-    ("exist") ("exists"."&exist;")
-    ("empty") ("emptyset"."&empty;")
-    ("nabla")
-    ("isin") ("in"."&isin;")
-    ("notin")
-    ("ni")
-    ("prod")
-    ("sum")
-    ("minus")
-    ("lowast") ("ast"."&lowast;")
-    ("radic")
-    ("prop") ("proptp"."&prop;")
-    ("infin") ("infty"."&infin;")
-    ("ang") ("angle"."&ang;")
-    ("and") ("wedge"."&and;")
-    ("or") ("vee"."&or;")
-    ("cap")
-    ("cup")
-    ("int")
-    ("there4")
-    ("sim")
-    ("cong") ("simeq"."&cong;")
-    ("asymp")("approx"."&asymp;")
-    ("ne") ("neq"."&ne;")
-    ("equiv")
-    ("le")
-    ("ge")
-    ("sub") ("subset"."&sub;")
-    ("sup") ("supset"."&sup;")
-    ("nsub")
-    ("sube")
-    ("supe")
-    ("oplus")
-    ("otimes")
-    ("perp")
-    ("sdot") ("cdot"."&sdot;")
-    ("lceil")
-    ("rceil")
-    ("lfloor")
-    ("rfloor")
-    ("lang")
-    ("rang")
-    ("loz") ("Diamond"."&loz;")
-    ("spades") ("spadesuit"."&spades;")
-    ("clubs") ("clubsuit"."&clubs;")
-    ("hearts") ("diamondsuit"."&hearts;")
-    ("diams") ("diamondsuit"."&diams;")
-    ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
-    ("quot")
-    ("amp")
-    ("lt")
-    ("gt")
-    ("OElig")
-    ("oelig")
-    ("Scaron")
-    ("scaron")
-    ("Yuml")
-    ("circ")
-    ("tilde")
-    ("ensp")
-    ("emsp")
-    ("thinsp")
-    ("zwnj")
-    ("zwj")
-    ("lrm")
-    ("rlm")
-    ("ndash")
-    ("mdash")
-    ("lsquo")
-    ("rsquo")
-    ("sbquo")
-    ("ldquo")
-    ("rdquo")
-    ("bdquo")
-    ("dagger")
-    ("Dagger")
-    ("permil")
-    ("lsaquo")
-    ("rsaquo")
-    ("euro")
-
-    ("arccos"."arccos")
-    ("arcsin"."arcsin")
-    ("arctan"."arctan")
-    ("arg"."arg")
-    ("cos"."cos")
-    ("cosh"."cosh")
-    ("cot"."cot")
-    ("coth"."coth")
-    ("csc"."csc")
-    ("deg"."deg")
-    ("det"."det")
-    ("dim"."dim")
-    ("exp"."exp")
-    ("gcd"."gcd")
-    ("hom"."hom")
-    ("inf"."inf")
-    ("ker"."ker")
-    ("lg"."lg")
-    ("lim"."lim")
-    ("liminf"."liminf")
-    ("limsup"."limsup")
-    ("ln"."ln")
-    ("log"."log")
-    ("max"."max")
-    ("min"."min")
-    ("Pr"."Pr")
-    ("sec"."sec")
-    ("sin"."sin")
-    ("sinh"."sinh")
-    ("sup"."sup")
-    ("tan"."tan")
-    ("tanh"."tanh")
-    )
-  "Entities for TeX->HTML translation.
-Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
-\"&ent;\".  An entry can also be a dotted pair like (\"ent\".\"&other;\").
-In that case, \"\\ent\" will be translated to \"&other;\".
-The list contains HTML entities for Latin-1, Greek and other symbols.
-It is supplemented by a number of commonly used TeX macros with appropriate
-translations.  There is currently no way for users to extend this.")
-
 ;;; General functions for all backends
 
 (defvar org-export-target-aliases nil
   "Alist of targets with invisible aliases.")
 (defvar org-export-preferred-target-alist nil
   "Alist of section id's with preferred aliases.")
+(defvar org-export-id-target-alist nil
+  "Alist of section id's with preferred aliases.")
 (defvar org-export-code-refs nil
-  "Alist of code references and line numbers")
+  "Alist of code references and line numbers.")
 
 (defun org-export-preprocess-string (string &rest parameters)
   "Cleanup STRING so that that the true exported has a more consistent source.
@@ -1254,15 +1030,20 @@ on this string to produce the exported version."
         (outline-regexp "\\*+ ")
         target-alist rtn)
 
-    (setq org-export-target-aliases nil)
-    (setq org-export-preferred-target-alist nil)
-    (setq org-export-code-refs nil)
+    (setq org-export-target-aliases nil
+         org-export-preferred-target-alist nil
+         org-export-id-target-alist nil
+         org-export-code-refs nil)
 
     (with-current-buffer (get-buffer-create " org-mode-tmp")
       (erase-buffer)
       (insert string)
       (setq case-fold-search t)
 
+      (let ((inhibit-read-only t))
+       (remove-text-properties (point-min) (point-max)
+                               '(read-only t)))
+
       ;; Remove license-to-kill stuff
       ;; The caller marks some stuff for killing, stuff that has been
       ;; used to create the page title, for example.
@@ -1282,7 +1063,7 @@ on this string to produce the exported version."
       (untabify (point-min) (point-max))
 
       ;; Handle include files, and call a hook
-      (org-export-handle-include-files)
+      (org-export-handle-include-files-recurse)
       (run-hooks 'org-export-preprocess-after-include-files-hook)
 
       ;; Get rid of archived trees
@@ -1296,12 +1077,21 @@ on this string to produce the exported version."
                                     (plist-get parameters :exclude-tags))
       (run-hooks 'org-export-preprocess-after-tree-selection-hook)
 
+      ;; Mark end of lists
+      (org-export-mark-list-ending backend)
+
+      ;; Export code blocks
+      (org-export-blocks-preprocess)
+
       ;; Handle source code snippets
       (org-export-replace-src-segments-and-examples backend)
 
       ;; Protect short examples marked by a leading colon
       (org-export-protect-colon-examples)
 
+      ;; Protected spaces
+      (org-export-convert-protected-spaces backend)
+
       ;; Normalize footnotes
       (when (plist-get parameters :footnotes)
        (org-footnote-normalize nil t))
@@ -1309,6 +1099,11 @@ on this string to produce the exported version."
       ;; Find all headings and compute the targets for them
       (setq target-alist (org-export-define-heading-targets target-alist))
 
+      (run-hooks 'org-export-preprocess-after-headline-targets-hook)
+
+      ;; Find HTML special classes for headlines
+      (org-export-remember-html-container-classes)
+
       ;; Get rid of drawers
       (org-export-remove-or-extract-drawers
        drawers (plist-get parameters :drawers) backend)
@@ -1333,6 +1128,7 @@ on this string to produce the exported version."
 
       ;; Select and protect backend specific stuff, throw away stuff
       ;; that is specific for other backends
+      (run-hooks 'org-export-preprocess-before-selecting-backend-code-hook)
       (org-export-select-backend-specific-text backend)
 
       ;; Protect quoted subtrees
@@ -1358,12 +1154,14 @@ on this string to produce the exported version."
 
       ;; Find matches for radio targets and turn them into internal links
       (org-export-mark-radio-links)
+      (run-hooks 'org-export-preprocess-after-radio-targets-hook)
 
       ;; Find all links that contain a newline and put them into a single line
       (org-export-concatenate-multiline-links)
 
       ;; Normalize links: Convert angle and plain links into bracket links
       ;; and expand link abbreviations
+      (run-hooks 'org-export-preprocess-before-normalizing-links-hook)
       (org-export-normalize-links)
 
       ;; Find all internal links.  If they have a fuzzy match (i.e. not
@@ -1375,7 +1173,8 @@ on this string to produce the exported version."
       (when (plist-get parameters :emph-multiline)
        (org-export-concatenate-multiline-emphasis))
 
-      ;; Remove special table lines
+      ;; Remove special table lines, and store alignment information
+      (org-store-forced-table-alignment)
       (when org-export-table-remove-special-lines
        (org-export-remove-special-table-lines))
 
@@ -1403,6 +1202,9 @@ on this string to produce the exported version."
       ;; Remove or replace comments
       (org-export-handle-comments (plist-get parameters :comments))
 
+      ;; Remove #+TBLFM and #+TBLNAME lines
+      (org-export-handle-table-metalines)
+      
       ;; Run the final hook
       (run-hooks 'org-export-preprocess-final-hook)
 
@@ -1419,40 +1221,55 @@ on this string to produce the exported version."
        p (or (next-single-property-change p :org-license-to-kill)
             (point-max))))))
 
+(defvar org-export-define-heading-targets-headline-hook nil
+  "Hook that is run when a headline was matched during target search.
+This is part of the preprocessing for export.")
+
 (defun org-export-define-heading-targets (target-alist)
   "Find all headings and define the targets for them.
-The new targets are added to TARGET-ALIST, which is also returned."
+The new targets are added to TARGET-ALIST, which is also returned.
+Also find all ID and CUSTOM_ID properties and store them."
   (goto-char (point-min))
   (org-init-section-numbers)
   (let ((re (concat "^" org-outline-regexp
-                   "\\| [ \t]*:\\(ID\\|CUSTOM_ID\\):[ \t]*\\([^ \t\r\n]+\\)"))
+                   "\\|"
+                   "^[ \t]*:\\(ID\\|CUSTOM_ID\\):[ \t]*\\([^ \t\r\n]+\\)"))
        level target last-section-target a id)
     (while (re-search-forward re nil t)
-      (if (match-end 2)
-         (progn
-           (setq id (org-match-string-no-properties 2))
-           (push (cons id target) target-alist)
-           (setq a (or (assoc last-section-target org-export-target-aliases)
-                       (progn
-                         (push (list last-section-target)
-                               org-export-target-aliases)
-                         (car org-export-target-aliases))))
-           (push (caar target-alist) (cdr a))
-           (when (equal (match-string 1) "CUSTOM_ID")
-             (if (not (assoc last-section-target
-                             org-export-preferred-target-alist))
-                 (push (cons last-section-target id)
-                       org-export-preferred-target-alist))))
-       (setq level (org-reduced-level
-                    (save-excursion (goto-char (point-at-bol))
-                                    (org-outline-level))))
-       (setq target (org-solidify-link-text
-                     (format "sec-%s" (org-section-number level))))
-       (setq last-section-target target)
-       (push (cons target target) target-alist)
-       (add-text-properties
-        (point-at-bol) (point-at-eol)
-        (list 'target target)))))
+      (org-if-unprotected-at (match-beginning 0)
+       (if (match-end 2)
+           (progn
+             (setq id (org-match-string-no-properties 2))
+             (push (cons id target) target-alist)
+             (setq a (or (assoc last-section-target org-export-target-aliases)
+                         (progn
+                           (push (list last-section-target)
+                                 org-export-target-aliases)
+                           (car org-export-target-aliases))))
+             (push (caar target-alist) (cdr a))
+             (when (equal (match-string 1) "CUSTOM_ID")
+               (if (not (assoc last-section-target
+                               org-export-preferred-target-alist))
+                   (push (cons last-section-target id)
+                         org-export-preferred-target-alist)))
+             (when (equal (match-string 1) "ID")
+               (if (not (assoc last-section-target
+                               org-export-id-target-alist))
+                   (push (cons last-section-target (concat "ID-" id))
+                         org-export-id-target-alist))))
+         (setq level (org-reduced-level
+                      (save-excursion (goto-char (point-at-bol))
+                                      (org-outline-level))))
+         (setq target (org-solidify-link-text
+                       (format "sec-%s" (replace-regexp-in-string
+                                         "\\." "_"
+                                         (org-section-number level)))))
+         (setq last-section-target target)
+         (push (cons target target) target-alist)
+         (add-text-properties
+          (point-at-bol) (point-at-eol)
+          (list 'target target))
+         (run-hooks 'org-export-define-heading-targets-headline-hook)))))
   target-alist)
 
 (defun org-export-handle-invisible-targets (target-alist)
@@ -1488,7 +1305,7 @@ This function also handles the id links, if they have a match in
 the current file."
   (goto-char (point-min))
   (while (re-search-forward org-bracket-link-regexp nil t)
-    (org-if-unprotected
+    (org-if-unprotected-at (1+ (match-beginning 0))
      (let* ((md (match-data))
            (desc (match-end 2))
            (link (org-link-unescape (match-string 1)))
@@ -1513,18 +1330,19 @@ the current file."
                   (string-match "^\\." link))
               nil)
              (t
-              (save-excursion
-                (setq found (condition-case nil (org-link-search link)
-                              (error nil)))
-                (when (and found
-                           (or (org-on-heading-p)
-                               (not (eq found 'dedicated))))
-                  (or (get-text-property (point) 'target)
-                      (get-text-property
-                       (max (point-min)
-                            (1- (or (previous-single-property-change
-                                     (point) 'target) 0)))
-                       'target))))))))
+              (let ((org-link-search-inhibit-query t))
+                (save-excursion
+                  (setq found (condition-case nil (org-link-search link)
+                                (error nil)))
+                  (when (and found
+                             (or (org-on-heading-p)
+                                 (not (eq found 'dedicated))))
+                    (or (get-text-property (point) 'target)
+                        (get-text-property
+                         (max (point-min)
+                              (1- (or (previous-single-property-change
+                                       (point) 'target) 0)))
+                         'target)))))))))
        (when target
         (set-match-data md)
         (goto-char (match-beginning 1))
@@ -1535,12 +1353,23 @@ the current file."
         (unless desc (insert "][" link))
         (add-text-properties pos (point) props))))))
 
+(defun org-export-remember-html-container-classes ()
+  "Store the HTML_CONTAINER_CLASS properties in a text property."
+  (goto-char (point-min))
+  (let (class)
+    (while (re-search-forward
+           "^[ \t]*:HTML_CONTAINER_CLASS:[ \t]+\\(.+\\)$" nil t)
+      (setq class (match-string 1))
+      (save-excursion
+       (org-back-to-heading t)
+       (put-text-property (point-at-bol) (point-at-eol) 'html-container-class class)))))
+
 (defvar org-export-format-drawer-function nil
   "Function to be called to format the contents of a drawer.
 The function must accept three parameters:
-  BACKEND  one of the symbols html, docbook, latex, ascii, xoxo
   NAME     the drawer name, like \"PROPERTIES\"
   CONTENT  the content of the drawer.
+  BACKEND  one of the symbols html, docbook, latex, ascii, xoxo
 The function should return the text to be inserted into the buffer.
 If this is nil, `org-export-format-drawer' is used as a default.")
 
@@ -1659,7 +1488,7 @@ from the buffer."
       (goto-char (point-min))
       (while (re-search-forward re-archive nil t)
        (if (not (org-on-heading-p t))
-           (org-end-of-subtree t)
+           (goto-char (point-at-eol))
          (beginning-of-line 1)
          (setq a (if export-archived-trees
                      (1+ (point-at-eol)) (point))
@@ -1713,6 +1542,26 @@ from the buffer."
       (add-text-properties (point) (org-end-of-subtree t)
                           '(org-protected t)))))
 
+(defun org-export-convert-protected-spaces (backend)
+  "Convert strings like \\____ to protected spaces in all backends."
+  (goto-char (point-min))
+  (while (re-search-forward "\\\\__+" nil t)
+    (org-if-unprotected-1
+     (replace-match
+      (org-add-props
+         (cond
+          ((eq backend 'latex)
+           (format "\\hspace{%dex}" (- (match-end 0) (match-beginning 0))))
+          ((eq backend 'html)
+           (org-add-props (match-string 0) nil
+             'org-whitespace (- (match-end 0) (match-beginning 0))))
+          ;; ((eq backend 'docbook))
+          ((eq backend 'ascii)
+           (org-add-props (match-string 0) '(org-whitespace t)))
+          (t (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
+         '(org-protected t))
+      t t))))
+
 (defun org-export-protect-verbatim ()
   "Mark verbatim snippets with the protection property."
   (goto-char (point-min))
@@ -1739,6 +1588,7 @@ from the buffer."
   (let ((formatters
         '((docbook "DOCBOOK" "BEGIN_DOCBOOK" "END_DOCBOOK")
           (html "HTML" "BEGIN_HTML" "END_HTML")
+          (beamer "BEAMER" "BEGIN_BEAMER" "END_BEAMER")
           (ascii "ASCII" "BEGIN_ASCII" "END_ASCII")
           (latex "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
        (case-fold-search t)
@@ -1746,15 +1596,25 @@ from the buffer."
 
     (while formatters
       (setq fmt (pop formatters))
-      (when (eq (car fmt) backend)
-       ;; This is selected code, put it into the file for real
-       (goto-char (point-min))
-       (while (re-search-forward (concat "^\\([ \t]*\\)#\\+" (cadr fmt)
-                                         ":[ \t]*\\(.*\\)") nil t)
+      ;; Handle #+Backend: stuff
+      (goto-char (point-min))
+      (while (re-search-forward (concat "^\\([ \t]*\\)#\\+" (cadr fmt)
+                                       ":[ \t]*\\(.*\\)") nil t)
+       (if (not (eq (car fmt) backend))
+           (delete-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
          (replace-match "\\1\\2" t)
          (add-text-properties
           (point-at-bol) (min (1+ (point-at-eol)) (point-max))
           '(org-protected t))))
+      ;; Delete #+attr_Backend: stuff of another backend. Those
+      ;; matching the current backend will be taken care of by
+      ;; `org-export-attach-captions-and-attributes'
+      (goto-char (point-min))
+      (while (re-search-forward (concat "^\\([ \t]*\\)#\\+attr_" (cadr fmt)
+                                       ":[ \t]*\\(.*\\)") nil t)
+       (when (not (eq (car fmt) backend))
+         (delete-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))))
+      ;; Handle #+begin_Backend and #+end_Backend stuff
       (goto-char (point-min))
       (while (re-search-forward (concat "^[ \t]*#\\+" (caddr fmt) "\\>.*\n?")
                                nil t)
@@ -1788,8 +1648,8 @@ These special cookies will later be interpreted by the backend."
       (setq beg (match-beginning 0)
            beg1 (1+ (match-end 0)))
       (when (re-search-forward (concat "^[ \t]*#\\+end_" type "\\>.*") nil t)
-       (setq end (1+ (point-at-eol))
-             end1 (1- (match-beginning 0)))
+       (setq end1 (1- (match-beginning 0))
+             end (+ (point-at-eol) (if (looking-at "\n$") 1 0)))
        (setq content (org-remove-indentation (buffer-substring beg1 end1)))
        (setq content (concat "ORG-" (upcase t1) "-START\n"
                              content "\n"
@@ -1797,6 +1657,31 @@ These special cookies will later be interpreted by the backend."
        (delete-region beg end)
        (insert (org-add-props content nil 'original-indentation ind))))))
 
+(defun org-export-mark-list-ending (backend)
+  "Mark list endings with special cookies.
+These special cookies will later be interpreted by the backend.
+`org-list-end-re' is replaced by a blank line in the process."
+  (let ((process-buffer
+        (lambda (end-list-marker)
+          (goto-char (point-min))
+          (while (org-search-forward-unenclosed org-item-beginning-re nil t)
+            (goto-char (org-list-bottom-point))
+            (when (and (not (eq org-list-ending-method 'indent))
+                       (looking-at (org-list-end-re)))
+              (replace-match "\n"))
+            (insert end-list-marker)))))
+  ;; We need to divide backends into 3 categories.
+  (cond
+   ;; 1. Backends using `org-list-parse-list' do not need markers.
+   ((memq backend '(latex))
+    nil)
+   ;; 2. Line-processing backends need to be told where lists end.
+   ((memq backend '(html docbook))
+    (funcall process-buffer "ORG-LIST-END\n"))
+   ;; 3. Others backends do not need to know this: clean list enders.
+   (t
+    (funcall process-buffer "")))))
+
 (defun org-export-attach-captions-and-attributes (backend target-alist)
   "Move #+CAPTION, #+ATTR_BACKEND, and #+LABEL text into text properties.
 If the next thing following is a table, add the text properties to the first
@@ -1811,38 +1696,55 @@ table line.  If it is a link, add it to the line containing the link."
                    "\\|"
                    "^[ \t]*#\\+label:[ \t]+\\(.*\\)"
                    "\\|"
-                   "^[ \t]*|[^-]"
+                   "^[ \t]*\\(|[^-]\\)"
                    "\\|"
                    "^[ \t]*\\[\\[.*\\]\\][ \t]*$"))
-       cap attr label)
+       cap shortn attr label end)
     (while (re-search-forward re nil t)
       (cond
        ((match-end 1)
-       (setq cap (concat cap (if cap " " "") (org-trim (match-string 1)))))
+       (progn
+         (setq cap (concat cap (if cap " " "") (org-trim (match-string 1))))
+         (when (string-match "\\[\\(.*\\)\\]{\\(.*\\)}" cap)
+           (setq shortn (match-string 1 cap)
+                 cap (match-string 2 cap)))
+         (delete-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))))
        ((match-end 2)
-       (setq attr (concat attr (if attr " " "") (org-trim (match-string 2)))))
+       (progn
+         (setq attr (concat attr (if attr " " "") (org-trim (match-string 2))))
+         (delete-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))))
        ((match-end 3)
-       (setq label (org-trim (match-string 3))))
+       (progn
+         (setq label (org-trim (match-string 3)))
+         (delete-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))))
        (t
-       (add-text-properties (point-at-bol) (point-at-eol)
+       (setq end (if (match-end 4)
+                     (let ((ee (org-table-end)))
+                       (prog1 (1- (marker-position ee)) (move-marker ee nil)))
+                   (point-at-eol)))
+       (add-text-properties (point-at-bol) end
                             (list 'org-caption cap
+                                  'org-caption-shortn shortn
                                   'org-attributes attr
                                   'org-label label))
        (if label (push (cons label label) target-alist))
+       (goto-char end)
        (setq cap nil attr nil label nil)))))
   target-alist)
 
 (defun org-export-remove-comment-blocks-and-subtrees ()
   "Remove the comment environment, and also commented subtrees."
   (let ((re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
-       (case-fold-search nil))
+       case-fold-search)
     ;; Remove comment environment
     (goto-char (point-min))
+    (setq case-fold-search t)
     (while (re-search-forward
-           "^#\\+BEGIN_COMMENT[ \t]*\n[^\000]*?^#\\+END_COMMENT\\>.*" nil t)
+           "^#\\+begin_comment[ \t]*\n[^\000]*?^#\\+end_comment\\>.*" nil t)
       (replace-match "" t t))
     ;; Remove subtrees that are commented
     (goto-char (point-min))
+    (setq case-fold-search nil)
     (while (re-search-forward re-commented nil t)
       (goto-char (match-beginning 0))
       (delete-region (point) (org-end-of-subtree t)))))
@@ -1851,21 +1753,36 @@ table line.  If it is a link, add it to the line containing the link."
   "Remove comments, or convert to backend-specific format.
 COMMENTSP can be a format string for publishing comments.
 When it is nil, all comments will be removed."
-  (let ((re "^\\(#\\|[ \t]*#\\+\\)\\(.*\n?\\)")
+  (let ((re "^\\(#\\|[ \t]*#\\+ \\)\\(.*\n?\\)")
+       pos)
+    (goto-char (point-min))
+    (while (or (looking-at re)
+              (re-search-forward re nil t))
+      (setq pos (match-beginning 0))
+      (if (get-text-property pos 'org-protected)
+         (goto-char (1+ pos))
+       (if (and commentsp
+                (not (equal (char-before (match-end 1)) ?+)))
+           (progn (add-text-properties
+                   (match-beginning 0) (match-end 0) '(org-protected t))
+                  (replace-match (format commentsp (match-string 2)) t t))
+         (goto-char (1+ pos))
+         (replace-match "")
+         (goto-char (max (point-min) (1- pos))))))))
+
+(defun org-export-handle-table-metalines ()
+  "Remove table specific metalines #+TBLNAME: and #+TBLFM:."
+  (let ((re "^[ \t]*#\\+TBL\\(NAME\\|FM\\):\\(.*\n?\\)")
        pos)
     (goto-char (point-min))
     (while (or (looking-at re)
               (re-search-forward re nil t))
       (setq pos (match-beginning 0))
-      (if (and commentsp
-              (not (equal (char-before (match-end 1)) ?+)))
-         (progn (add-text-properties
-                 (match-beginning 0) (match-end 0) '(org-protected t))
-                (replace-match (format commentsp (match-string 2)) t t))
+      (if (get-text-property (match-beginning 1) 'org-protected)
+         (goto-char (1+ pos))
        (goto-char (1+ pos))
-       (org-if-unprotected
-        (replace-match "")
-        (goto-char (max (point-min) (1- pos))))))))
+       (replace-match "")
+       (goto-char (max (point-min) (1- pos)))))))
 
 (defun org-export-mark-radio-links ()
   "Find all matches for radio targets and turn them into internal links."
@@ -1877,30 +1794,54 @@ When it is nil, all comments will be removed."
        (unless
            (save-match-data
              (or (org-in-regexp org-bracket-link-regexp)
-                 (org-in-regexp org-plain-link-re)))
+                 (org-in-regexp org-plain-link-re)
+                 (org-in-regexp "<<[^<>]+>>")))
          (org-if-unprotected
           (replace-match "\\1[[\\2]]")))))))
 
+(defun org-store-forced-table-alignment ()
+  "Find table lines which force alignment, store the results in properties."
+  (let (line cnt aligns)
+    (goto-char (point-min))
+    (while (re-search-forward "|[ \t]*<[lrc][0-9]*>[ \t]*|" nil t)
+      ;; OK, this looks like a table line with an alignment cookie
+      (org-if-unprotected
+       (setq line (buffer-substring (point-at-bol) (point-at-eol)))
+       (when (and (org-at-table-p)
+                 (org-table-cookie-line-p line))
+        (setq cnt 0 aligns nil)
+        (mapc
+         (lambda (x)
+           (setq cnt (1+ cnt))
+           (if (string-match "\\`<\\([lrc]\\)" x)
+               (push (cons cnt (downcase (match-string 1 x))) aligns)))
+         (org-split-string line "[ \t]*|[ \t]*"))
+        (add-text-properties (org-table-begin) (org-table-end)
+                             (list 'org-forced-aligns aligns))))
+      (goto-char (point-at-eol)))))
+
 (defun org-export-remove-special-table-lines ()
-  "Remove tables lines that are used for internal purposes."
+  "Remove tables lines that are used for internal purposes.
+Also, store forcedalignment information found in such lines."
   (goto-char (point-min))
   (while (re-search-forward "^[ \t]*|" nil t)
-    (beginning-of-line 1)
-    (if (or (looking-at "[ \t]*| *[!_^] *|")
-           (not 
-            (memq
-             nil
-             (mapcar
-              (lambda (f)
-                (or (= (length f) 0)
-                    (string-match
-                     "\\`<\\([0-9]\\|[rl]\\|[rl][0-9]+\\)>\\'" f)))
-              (org-split-string ;; FIXME, can't we do this without splitting???
-               (buffer-substring (point-at-bol) (point-at-eol))
-               "[ \t]*|[ \t]*")))))
-       (delete-region (max (point-min) (1- (point-at-bol)))
-                      (point-at-eol))
-      (end-of-line 1))))
+    (org-if-unprotected-at (1- (point))
+      (beginning-of-line 1)
+      (if (or (looking-at "[ \t]*| *[!_^] *|")
+             (not
+              (memq
+               nil
+               (mapcar
+                (lambda (f)
+                  (or (= (length f) 0)
+                      (string-match
+                       "\\`<\\([0-9]\\|[lrc]\\|[lrc][0-9]+\\)>\\'" f)))
+                (org-split-string ;; FIXME, can't we do without splitting???
+                 (buffer-substring (point-at-bol) (point-at-eol))
+                 "[ \t]*|[ \t]*")))))
+         (delete-region (max (point-min) (1- (point-at-bol)))
+                        (point-at-eol))
+       (end-of-line 1)))))
 
 (defun org-export-protect-sub-super (s)
   (save-match-data
@@ -1915,16 +1856,19 @@ When it is nil, all comments will be removed."
        nodesc)
     (goto-char (point-min))
     (while (re-search-forward re-plain-link nil t)
-      (goto-char (1- (match-end 0)))
-      (org-if-unprotected-at (1+ (match-beginning 0))
-       (let* ((s (concat (match-string 1)
-                        "[[" (match-string 2) ":" (match-string 3)
-                        "][" (match-string 2) ":" (org-export-protect-sub-super
-                                                   (match-string 3))
-                        "]]")))
-        ;; added 'org-link face to links
-        (put-text-property 0 (length s) 'face 'org-link s)
-        (replace-match s t t))))
+      (unless (org-string-match-p
+              "\\[\\[\\S+:\\S-*?\\<"
+              (buffer-substring (point-at-bol) (match-beginning 0)))
+       (goto-char (1- (match-end 0)))
+       (org-if-unprotected-at (1+ (match-beginning 0))
+         (let* ((s (concat (match-string 1)
+                           "[[" (match-string 2) ":" (match-string 3)
+                           "][" (match-string 2) ":" (org-export-protect-sub-super
+                                                      (match-string 3))
+                           "]]")))
+           ;; added 'org-link face to links
+           (put-text-property 0 (length s) 'face 'org-link s)
+           (replace-match s t t)))))
     (goto-char (point-min))
     (while (re-search-forward re-angle-link nil t)
       (goto-char (1- (match-end 0)))
@@ -1962,7 +1906,7 @@ This is to make sure that the line-processing export backends
 can work correctly."
   (goto-char (point-min))
   (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
-    (org-if-unprotected
+    (org-if-unprotected-at (match-beginning 1)
      (replace-match "\\1 \\3")
      (goto-char (match-beginning 0)))))
 
@@ -1975,7 +1919,9 @@ can work correctly."
     (if (and (not (= (char-after (match-beginning 3))
                     (char-after (match-beginning 4))))
             (save-excursion (goto-char (match-beginning 0))
-                            (save-match-data (not (org-at-table-p)))))
+                            (save-match-data
+                              (and (not (org-at-table-p))
+                                   (not (org-at-heading-p))))))
        (org-if-unprotected
         (subst-char-in-region (match-beginning 0) (match-end 0)
                               ?\n ?\  t)
@@ -2144,16 +2090,15 @@ TYPE must be a string, any of:
                                       (intern (concat ":" key)))))
          (save-match-data
            (when args
-             (setq args (org-split-string args ",[ \t\n]*") args2 nil)
-             (setq args (mapcar 'org-trim args))
+             (setq args (org-split-string args ",") args2 nil)
              (while args
                (while (string-match "\\\\\\'" (car args))
                  ;; repair bad splits
                  (setcar (cdr args) (concat (substring (car args) 0 -1)
-                                            ";" (nth 1 args)))
+                                            "," (nth 1 args)))
                  (pop args))
                (push (pop args) args2))
-             (setq args (nreverse args2))
+             (setq args (mapcar 'org-trim (nreverse args2)))
              (setq s 0)
              (while (string-match "\\$\\([0-9]+\\)" val s)
                (setq s (1+ (match-beginning 0))
@@ -2181,12 +2126,13 @@ TYPE must be a string, any of:
 (defun org-export-handle-include-files ()
   "Include the contents of include files, with proper formatting."
   (let ((case-fold-search t)
-       params file markup lang start end prefix prefix1 switches)
+       params file markup lang start end prefix prefix1 switches all minlevel)
     (goto-char (point-min))
     (while (re-search-forward "^#\\+INCLUDE:?[ \t]+\\(.*\\)" nil t)
       (setq params (read (concat "(" (match-string 1) ")"))
            prefix (org-get-and-remove-property 'params :prefix)
            prefix1 (org-get-and-remove-property 'params :prefix1)
+           minlevel (org-get-and-remove-property 'params :minlevel)
            file (org-symname-or-string (pop params))
            markup (org-symname-or-string (pop params))
            lang (and (member markup '("src" "SRC"))
@@ -2198,6 +2144,7 @@ TYPE must be a string, any of:
              (not (file-exists-p file))
              (not (file-readable-p file)))
          (insert (format "CANNOT INCLUDE FILE %s" file))
+       (setq all (cons file all))
        (when markup
          (if (equal (downcase markup) "src")
              (setq start (format "#+begin_src %s %s\n"
@@ -2208,11 +2155,24 @@ TYPE must be a string, any of:
                  end  (format "#+end_%s" markup))))
        (insert (or start ""))
        (insert (org-get-file-contents (expand-file-name file)
-                                      prefix prefix1 markup))
+                                      prefix prefix1 markup minlevel))
        (or (bolp) (newline))
-       (insert (or end ""))))))
-
-(defun org-get-file-contents (file &optional prefix prefix1 markup)
+       (insert (or end ""))))
+    all))
+
+(defun org-export-handle-include-files-recurse ()
+  "Recursively include files aborting on circular inclusion."
+  (let ((now (list org-current-export-file)) all)
+    (while now
+      (setq all (append now all))
+      (setq now (org-export-handle-include-files))
+      (let ((intersection
+            (delq nil
+                  (mapcar (lambda (el) (when (member el all) el)) now))))
+       (when intersection
+         (error "Recursive #+INCLUDE: %S" intersection))))))
+
+(defun org-get-file-contents (file &optional prefix prefix1 markup minlevel)
   "Get the contents of FILE and return them as a string.
 If PREFIX is a string, prepend it to each line.  If PREFIX1
 is a string, prepend it to the first line instead of PREFIX.
@@ -2225,7 +2185,7 @@ take care of the block they are in."
       (goto-char (point-min))
       (while (not (eobp))
        (insert (or prefix1 prefix))
-       (setq prefix1 nil)
+       (setq prefix1 "")
        (beginning-of-line 2)))
     (buffer-string)
     (when (member markup '("src" "example"))
@@ -2234,6 +2194,9 @@ take care of the block they are in."
        (goto-char (match-beginning 0))
        (insert ",")
        (end-of-line 1)))
+    (when minlevel
+      (dotimes (lvl minlevel)
+       (org-map-region 'org-demote (point-min) (point-max))))
     (buffer-string)))
 
 (defun org-get-and-remove-property (listvar prop)
@@ -2263,24 +2226,36 @@ in the list) and remove property and value from the list in LISTVAR."
   "Replace source code segments with special code for export."
   (setq org-export-last-code-line-counter-value 0)
   (let ((case-fold-search t)
-       lang code trans opts indent)
+       lang code trans opts indent caption)
     (goto-char (point-min))
     (while (re-search-forward
-           "\\(^\\([ \t]*\\)#\\+BEGIN_SRC:?[ \t]+\\([^ \t\n]+\\)\\(.*\\)\n\\([^\000]+?\n\\)[ \t]*#\\+END_SRC.*\\)\\|\\(^\\([ \t]*\\)#\\+BEGIN_EXAMPLE:?\\(?:[ \t]+\\(.*\\)\\)?\n\\([^\000]+?\n\\)[ \t]*#\\+END_EXAMPLE.*\\)"
+           "\\(^\\([ \t]*\\)#\\+BEGIN_SRC:?\\([ \t]+\\([^ \t\n]+\\)\\)?\\(.*\\)\n\\([^\000]+?\n\\)[ \t]*#\\+END_SRC.*\n?\\)\\|\\(^\\([ \t]*\\)#\\+BEGIN_EXAMPLE:?\\(?:[ \t]+\\(.*\\)\\)?\n\\([^\000]+?\n\\)[ \t]*#\\+END_EXAMPLE.*\n?\\)"
            nil t)
       (if (match-end 1)
-         ;; src segments
-         (setq lang (match-string 3)
-               opts (match-string 4)
-               code (match-string 5)
-               indent (length (match-string 2)))
+         (if (not (match-string 4))
+             (error "Source block missing language specification: %s"
+                    (let* ((body (match-string 6))
+                           (nothing (message "body:%s" body))
+                           (preview (or (and (string-match
+                                              "^[ \t]*\\([^\n\r]*\\)" body)
+                                             (match-string 1 body)) body)))
+                      (if (> (length preview) 35)
+                          (concat (substring preview 0 32) "...")
+                        preview)))
+           ;; src segments
+           (setq lang (match-string 4)
+                 opts (match-string 5)
+                 code (match-string 6)
+                 indent (length (match-string 2))
+                 caption (get-text-property 0 'org-caption (match-string 0))))
        (setq lang nil
-             opts (match-string 8)
-             code (match-string 9)
-             indent (length (match-string 7))))
+             opts (match-string 9)
+             code (match-string 10)
+             indent (length (match-string 8))
+              caption (get-text-property 0 'org-caption (match-string 0))))
 
       (setq trans (org-export-format-source-code-or-example
-                  backend lang code opts indent))
+                  backend lang code opts indent caption))
       (replace-match trans t t))))
 
 (defvar htmlp)  ;; dynamically scoped
@@ -2288,9 +2263,10 @@ in the list) and remove property and value from the list in LISTVAR."
 (defvar org-export-latex-verbatim-wrap) ;; defined in org-latex.el
 (defvar org-export-latex-listings) ;; defined in org-latex.el
 (defvar org-export-latex-listings-langs) ;; defined in org-latex.el
-
+(defvar org-export-latex-listings-w-names) ;; defined in org-latex.el
+(defvar org-export-latex-minted-langs) ;; defined in org-latex.el
 (defun org-export-format-source-code-or-example
-  (backend lang code &optional opts indent)
+  (backend lang code &optional opts indent caption)
   "Format CODE from language LANG and return it formatted for export.
 If LANG is nil, do not add any fontification.
 OPTS contains formatting options, like `-n' for triggering numbering lines,
@@ -2341,13 +2317,15 @@ INDENT was the original indentation of the block."
              (concat "\n#+BEGIN_DOCBOOK\n"
                      (org-add-props (concat "<programlisting><![CDATA["
                                             rtn
-                                            "]]>\n</programlisting>\n")
-                         '(org-protected t))
+                                            "]]></programlisting>\n")
+                         '(org-protected t org-example t))
                      "#+END_DOCBOOK\n"))
             ((eq backend 'html)
              ;; We are exporting to HTML
              (when lang
-               (require 'htmlize nil t)
+               (if (featurep 'xemacs)
+                   (require 'htmlize)
+                 (require 'htmlize nil t))
                (when (not (fboundp 'htmlize-region-for-paste))
                  ;; we do not have htmlize.el, or an old version of it
                  (setq lang nil)
@@ -2378,12 +2356,22 @@ INDENT was the original indentation of the block."
                            (org-export-htmlize-region-for-paste
                             (point-min) (point-max))))
                    (if (string-match "<pre\\([^>]*\\)>\n*" rtn)
-                       (setq rtn (replace-match
-                                  (format "<pre class=\"src src-%s\">\n" lang)
-                                  t t rtn))))
+                       (setq rtn
+                              (concat
+                               (if caption
+                                   (concat
+                                    "<div class=\"org-src-container\">"
+                                    (format
+                                     "<label class=\"org-src-name\">%s</label>"
+                                     caption))
+                                 "")
+                               (replace-match
+                                (format "<pre class=\"src src-%s\">\n" lang)
+                                t t rtn)
+                               (if caption "</div>" "")))))
                (if textareap
                    (setq rtn (concat
-                              (format "<p>\n<textarea cols=\"%d\" rows=\"%d\" overflow-x:scroll >\n"
+                              (format "<p>\n<textarea cols=\"%d\" rows=\"%d\">"
                                       cols rows)
                               rtn "</textarea>\n</p>\n"))
                  (with-temp-buffer
@@ -2400,34 +2388,60 @@ INDENT was the original indentation of the block."
                                                   cont rpllbl fmt)))
              (if (string-match "\\(\\`<[^>]*>\\)\n" rtn)
                  (setq rtn (replace-match "\\1" t nil rtn)))
-             (concat "\n#+BEGIN_HTML\n" (org-add-props rtn '(org-protected t)) "\n#+END_HTML\n\n"))
+             (concat "\n#+BEGIN_HTML\n" (org-add-props rtn '(org-protected t org-example t)) "\n#+END_HTML\n\n"))
             ((eq backend 'latex)
              (setq rtn (org-export-number-lines rtn 'latex 0 0 num cont rpllbl fmt))
-             (concat "\n#+BEGIN_LaTeX\n"
+             (concat "#+BEGIN_LaTeX\n"
                      (org-add-props
-                          (if org-export-latex-listings
-                              (concat
-                               (if lang
-                                   (let*
-                                      ((lang-sym (intern lang))
-                                       (lstlang
-                                        (or (cadr
-                                             (assq
-                                              lang-sym
-                                              org-export-latex-listings-langs))
-                                            lang)))
-                                     (format "\\lstset{language=%s}\n" lstlang))
-                                 "")
-                               "\\begin{lstlisting}\n"
-                               rtn "\\end{lstlisting}\n")
-                            (concat (car org-export-latex-verbatim-wrap)
-                                    rtn (cdr org-export-latex-verbatim-wrap)))
-                         '(org-protected t))
-                     "#+END_LaTeX\n\n"))
-            ((eq backend 'ascii)
-             ;; This is not HTML or LaTeX, so just make it an example.
-             (setq rtn (org-export-number-lines rtn 'ascii 0 0 num cont rpllbl fmt))
-             (concat "#+BEGIN_ASCII\n"
+                          (cond
+                          ((and org-export-latex-listings
+                                (not (eq org-export-latex-listings 'minted)))
+                           (concat
+                            (if lang
+                                (let*
+                                    ((lang-sym (intern lang))
+                                     (lstlang
+                                      (or (cadr
+                                           (assq
+                                            lang-sym
+                                            org-export-latex-listings-langs))
+                                          lang)))
+                                  (format "\\lstset{language=%s}\n" lstlang))
+                              "\n")
+                            (when (and caption
+                                       org-export-latex-listings-w-names)
+                              (format "\n%s $\\equiv$ \n"
+                                      (replace-regexp-in-string
+                                       "_" "\\\\_" caption)))
+                            "\\begin{lstlisting}\n"
+                            rtn "\\end{lstlisting}\n"))
+                          ((eq org-export-latex-listings 'minted)
+                           (if lang
+                               (let*
+                                   ((lang-sym (intern lang))
+                                    (minted-lang
+                                     (or (cadr
+                                          (assq
+                                           lang-sym
+                                           org-export-latex-minted-langs))
+                                         (downcase lang))))
+                                 (concat
+                                  (when (and caption
+                                             org-export-latex-listings-w-names)
+                                    (format "\n%s $\\equiv$ \n"
+                                            (replace-regexp-in-string
+                                             "_" "\\\\_" caption)))
+                                  (format "\\begin{minted}{%s}\n" minted-lang)
+                                  rtn "\\end{minted}\n"))))
+                           (t (concat (car org-export-latex-verbatim-wrap)
+                                      rtn (cdr org-export-latex-verbatim-wrap))))
+                          '(org-protected t org-example t))
+                         "#+END_LaTeX\n"))
+             ((eq backend 'ascii)
+              ;; This is not HTML or LaTeX, so just make it an example.
+              (setq rtn (org-export-number-lines rtn 'ascii 0 0 num cont rpllbl fmt))
+              (concat caption "\n"
+                     "#+BEGIN_ASCII\n"
                      (org-add-props
                          (concat
                           (mapconcat
@@ -2435,7 +2449,7 @@ INDENT was the original indentation of the block."
                            (org-split-string rtn "\n")
                            "\n")
                           "\n")
-                         '(org-protected t))
+                         '(org-protected t org-example t))
                      "#+END_ASCII\n"))))
       (org-add-props rtn nil 'original-indentation indent))))
 
@@ -2538,22 +2552,27 @@ INDENT was the original indentation of the block."
 (defun org-export-visible (type arg)
   "Create a copy of the visible part of the current buffer, and export it.
 The copy is created in a temporary buffer and removed after use.
-TYPE is the final key (as a string) that also select the export command in
-the `C-c C-e' export dispatcher.
-
-As a special case, if you type SPC at the prompt, the temporary org-mode
-file will not be removed but presented to you so that you can continue to
-use it.  The prefix arg ARG is passed through to the exporting command."
+TYPE is the final key (as a string) that also selects the export command in
+the \\<org-mode-map>\\[org-export] export dispatcher.
+As a special case, if the you type SPC at the prompt, the temporary
+org-mode file will not be removed but presented to you so that you can
+continue to use it.  The prefix arg ARG is passed through to the exporting
+command."
   (interactive
    (list (progn
-          (message "Export visible: [a]SCII  [h]tml  [b]rowse HTML [H/R]uffer with HTML  [D]ocBook  [x]OXO  [ ]keep buffer")
+          (message "Export visible: [a]SCII  [h]tml  [b]rowse HTML [H/R]buffer with HTML  [D]ocBook  [l]atex  [p]df  [d]view pdf  [L]atex buffer  [x]OXO  [ ]keep buffer")
           (read-char-exclusive))
         current-prefix-arg))
-  (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?D ?x ?\ )))
+  (if (not (member type '(?a ?n ?u ?\C-a ?b ?\C-b ?h ?D ?x ?\ ?l ?p ?d ?L)))
       (error "Invalid export key"))
   (let* ((binding (cdr (assoc type
-                             '((?a . org-export-as-ascii)
+                             '(
+                               (?a . org-export-as-ascii)
                                (?A . org-export-as-ascii-to-buffer)
+                               (?n . org-export-as-latin1)
+                               (?N . org-export-as-latin1-to-buffer)
+                               (?u . org-export-as-utf8)
+                               (?U . org-export-as-utf8-to-buffer)
                                (?\C-a . org-export-as-ascii)
                                (?b . org-export-as-html-and-open)
                                (?\C-b . org-export-as-html-and-open)
@@ -2561,6 +2580,12 @@ use it.  The prefix arg ARG is passed through to the exporting command."
                                (?H . org-export-as-html-to-buffer)
                                (?R . org-export-region-as-html)
                                (?D . org-export-as-docbook)
+
+                               (?l . org-export-as-latex)
+                               (?p . org-export-as-pdf)
+                               (?d . org-export-as-pdf-and-open)
+                               (?L . org-export-as-latex-to-buffer)
+
                                (?x . org-export-as-xoxo)))))
         (keepp (equal type ?\ ))
         (file buffer-file-name)
@@ -2587,9 +2612,10 @@ use it.  The prefix arg ARG is passed through to the exporting command."
        ;; does do the trick.
        (if (looking-at "#[^\r\n]*")
            (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
-       (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
-         (append-to-buffer buffer (1+ (match-beginning 0))
-                           (min (point-max) (1+ (match-end 0))))))
+       (when (re-search-forward "^\\*+[ \t]+" nil t)
+         (while (re-search-backward "[\n\r]#[^\n\r]*" nil t)
+           (append-to-buffer buffer (1+ (match-beginning 0))
+                             (min (point-max) (1+ (match-end 0)))))))
       (set-buffer buffer)
       (let ((buffer-file-name file)
            (org-inhibit-startup t))
@@ -2614,6 +2640,28 @@ use it.  The prefix arg ARG is passed through to the exporting command."
 
 (defvar org-export-htmlized-org-css-url) ;; defined in org-html.el
 
+(defun org-export-string (string fmt &optional dir)
+  "Export STRING to FMT using existing export facilities.
+During export STRING is saved to a temporary file whose location
+could vary.  Optional argument DIR can be used to force the
+directory in which the temporary file is created during export
+which can be useful for resolving relative paths.  Dir defaults
+to the value of `temporary-file-directory'."
+  (let ((temporary-file-directory (or dir temporary-file-directory))
+       (tmp-file (make-temp-file "org-")))
+    (unwind-protect
+       (with-temp-buffer
+         (insert string)
+         (write-file tmp-file)
+         (org-load-modules-maybe)
+         (unless org-local-vars
+           (setq org-local-vars (org-get-local-variables)))
+         (eval ;; convert to fmt -- mimicing `org-run-like-in-org-mode'
+          (list 'let org-local-vars
+                (list (intern (concat "org-export-as-" fmt))
+                      nil nil nil ''string t))))
+      (delete-file tmp-file))))
+
 ;;;###autoload
 (defun org-export-as-org (arg &optional hidden ext-plist
                              to-buffer body-only pub-dir)
@@ -2655,7 +2703,8 @@ directory."
                          filename)))
         (backup-inhibited t)
         (buffer (find-file-noselect filename))
-        (region (buffer-string)))
+        (region (buffer-string))
+         str-ret)
     (save-excursion
       (switch-to-buffer buffer)
       (erase-buffer)
@@ -2701,7 +2750,11 @@ directory."
            (write-file (concat filename ".html")))
          (kill-buffer newbuf)))
       (set-buffer-modified-p nil)
-      (kill-buffer (current-buffer)))))
+      (if (equal to-buffer 'string)
+          (progn (setq str-ret (buffer-string))
+                 (kill-buffer (current-buffer))
+                 str-ret)
+        (kill-buffer (current-buffer))))))
 
 (defvar org-archive-location)  ;; gets loaded with the org-archive require.
 (defun org-get-current-options ()
@@ -2723,6 +2776,7 @@ Does include HTML export options as well as TODO and CATEGORY stuff."
 #+EXPORT_EXCLUDE_TAGS: %s
 #+LINK_UP:   %s
 #+LINK_HOME: %s
+#+XSLT: 
 #+CATEGORY:  %s
 #+SEQ_TODO:  %s
 #+TYP_TODO:  %s
@@ -2815,13 +2869,16 @@ If yes remove the column and the special lines."
                                "^[ \t]*| *\\([\#!$*_^ /]\\) *|")
                              x)))
             lines))
+      ;; No special marking column
       (progn
        (setq org-table-clean-did-remove-column nil)
        (delq nil
              (mapcar
               (lambda (x)
                 (cond
-                 ((string-match  "^[ \t]*| */ *|" x)
+                 ((org-table-colgroup-line-p x)
+                  ;; This line contains colgroup info, extract it
+                  ;; and then discard the line
                   (setq org-table-colgroup-info
                         (mapcar (lambda (x)
                                   (cond ((member x '("<" "&lt;")) :start)
@@ -2830,14 +2887,20 @@ If yes remove the column and the special lines."
                                         (t nil)))
                                 (org-split-string x "[ \t]*|[ \t]*")))
                   nil)
+                 ((org-table-cookie-line-p x)
+                  ;; This line contains formatting cookies, discard it
+                  nil)
                  (t x)))
               lines)))
+    ;; there is a special marking column
     (setq org-table-clean-did-remove-column t)
     (delq nil
          (mapcar
           (lambda (x)
             (cond
-             ((string-match  "^[ \t]*| */ *|" x)
+             ((org-table-colgroup-line-p x)
+              ;; This line contains colgroup info, extract it
+              ;; and then discard the line
               (setq org-table-colgroup-info
                     (mapcar (lambda (x)
                               (cond ((member x '("<" "&lt;")) :start)
@@ -2846,8 +2909,12 @@ If yes remove the column and the special lines."
                                     (t nil)))
                             (cdr (org-split-string x "[ \t]*|[ \t]*"))))
               nil)
+             ((org-table-cookie-line-p x)
+              ;; This line contains formatting cookies, discard it
+              nil)
              ((string-match "^[ \t]*| *[!_^/] *|" x)
-              nil) ; ignore this line
+              ;; ignore this line
+              nil)
              ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
                   (string-match "^\\([ \t]*\\)|[^|]*|" x))
               ;; remove the first column
@@ -2857,7 +2924,7 @@ If yes remove the column and the special lines."
 (defun org-export-cleanup-toc-line (s)
   "Remove tags and timestamps from lines going into the toc."
   (when (memq org-export-with-tags '(not-in-toc nil))
-    (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
+    (if (string-match (org-re " +:[[:alnum:]_@#%:]+: *$") s)
        (setq s (replace-match "" t t s))))
   (when org-export-remove-timestamps-from-toc
     (while (string-match org-maybe-keyword-time-regexp s)
@@ -2869,41 +2936,6 @@ If yes remove the column and the special lines."
     (setq s (replace-match "" t t s)))
   s)
 
-(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-get-text-property-any (pos prop &optional object)
   (or (get-text-property pos prop object)