diff --git a/AUTHORS.md b/AUTHORS.md
--- a/AUTHORS.md
+++ b/AUTHORS.md
@@ -1,5 +1,6 @@
 # Contributors
 
+- Anabra
 - Arata Mizuki
 - Aaron Wolen
 - Albert Krewinkel
@@ -49,6 +50,7 @@
 - Emily Eisenberg
 - Eric Kow
 - Eric Seidel
+- Étienne Bersac
 - Felix Yan
 - Florian Eitel
 - Francesco Occhipinti
@@ -188,6 +190,7 @@
 - lwolfsonkin
 - nkalvi
 - oltolm
+- quasicomputational
 - qerub
 - robabla
 - roblabla
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -205,6 +205,10 @@
 Profiling
 ---------
 
+To diagnose a performance issue with parsing, first try using
+the `--trace` option.  This will give you a record of when block
+parsers succeed, so you can spot backtracking issues.
+
 To use the GHC profiler with cabal:
 
     cabal clean
diff --git a/COPYRIGHT b/COPYRIGHT
--- a/COPYRIGHT
+++ b/COPYRIGHT
@@ -69,8 +69,9 @@
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 ----------------------------------------------------------------------
-Pandoc's templates (in `data/templates`) are dual-licensed GPL (v2 or
-higher, same as pandoc) and the BSD 3-clause license.
+Pandoc's templates (in `data/templates`) are dual-licensed as either
+GPL (v2 or higher, same as pandoc) or (at your option) the BSD
+3-clause license.
 
 Copyright (c) 2014--2018, John MacFarlane
 
@@ -119,28 +120,32 @@
 Released under the GNU General Public License version 2 or later.
 
 ----------------------------------------------------------------------
-src/Text/Pandoc/Readers/Org.hs
-src/Text/Pandoc/Readers/Org/*
-test/Tests/Readers/Org/*
-Copyright (C) 2014-2018 Albert Krewinkel
+src/Text/Pandoc/Readers/TikiWiki.hs
+Copyright (C) 2017 Robin Lee Powell
 
+Released under the GNU General Public License version 2.
+
+----------------------------------------------------------------------
+src/Text/Pandoc/Readers/JATS.hs
+Copyright (C) 2017-2018 Hamish Mackenzie
+
 Released under the GNU General Public License version 2 or later.
 
 ----------------------------------------------------------------------
-data/LaTeXMathML.js
-Adapted by Jeff Knisely and Douglas Woodall from
-ASCIIMathML.js v. 1.4.7
-Copyright (C) 2005 Peter Jipsen
+src/Text/Pandoc/Readers/EPUB.hs
+Copyright (C) 2014-2018 Matthew Pickering
 
 Released under the GNU General Public License version 2 or later.
 
 ----------------------------------------------------------------------
-data/MathMLinHTML.js
-Copyright (C) 2004 Peter Jipsen http://www.chapman.edu/~jipsen
+src/Text/Pandoc/Readers/Org.hs
+src/Text/Pandoc/Readers/Org/*
+test/Tests/Readers/Org/*
+Copyright (C) 2014-2018 Albert Krewinkel
 
 Released under the GNU General Public License version 2 or later.
 
-------------------------------------------------------------------------
+----------------------------------------------------------------------
 data/pandoc.lua
 Copyright (C) 2017-2018 Albert Krewinkel
 
diff --git a/MANUAL.txt b/MANUAL.txt
--- a/MANUAL.txt
+++ b/MANUAL.txt
@@ -1,6 +1,6 @@
 % Pandoc User's Guide
 % John MacFarlane
-% March 17, 2018
+% April 26, 2018
 
 Synopsis
 ========
@@ -13,37 +13,19 @@
 Pandoc is a [Haskell] library for converting from one markup format to
 another, and a command-line tool that uses this library.
 
-Pandoc can read [Markdown], [CommonMark], [PHP Markdown Extra],
-[GitHub-Flavored Markdown], [MultiMarkdown], and (subsets of) [Textile],
-[reStructuredText], [HTML], [LaTeX], [MediaWiki markup], [TWiki
-markup], [TikiWiki markup], [Creole 1.0], [Haddock markup], [OPML],
-[Emacs Org mode], [DocBook], [JATS], [Muse], [txt2tags], [Vimwiki],
-[EPUB], [ODT], and [Word docx].
-
-Pandoc can write plain text, [Markdown],
-[CommonMark], [PHP Markdown Extra], [GitHub-Flavored Markdown],
-[MultiMarkdown], [reStructuredText], [XHTML], [HTML5], [LaTeX]
-\(including [`beamer`] slide shows\), [ConTeXt], [RTF], [OPML],
-[DocBook], [JATS], [OpenDocument], [ODT], [Word docx], [GNU Texinfo],
-[MediaWiki markup], [DokuWiki markup], [ZimWiki markup], [Haddock
-markup], [EPUB] \(v2 or v3\), [FictionBook2], [Textile], [groff man],
-[groff ms], [Emacs Org mode], [AsciiDoc], [InDesign ICML], [TEI
-Simple], [Muse], [PowerPoint] slide shows and [Slidy], [Slideous],
-[DZSlides], [reveal.js] or [S5] HTML slide shows. It can also produce
-[PDF] output on systems where LaTeX, ConTeXt, `pdfroff`,
-`wkhtmltopdf`, `prince`, or `weasyprint` is installed.
+Pandoc can convert between numerous markup and word processing formats,
+including, but not limited to, various flavors of [Markdown], [HTML],
+[LaTeX] and [Word docx]. For the full lists of input and output formats,
+see the `--from` and `--to` [options below][General options].
+Pandoc can also produce [PDF] output: see [creating a PDF], below.
 
 Pandoc's enhanced version of Markdown includes syntax for [tables],
-[definition lists], [metadata blocks], [`Div` blocks][Extension:
-`fenced_divs`], [footnotes] and [citations], embedded
-[LaTeX][Extension: `raw_tex`] (including [math]), [Markdown inside HTML
-block elements][Extension: `markdown_in_html_blocks`], and much more.
-These enhancements, described further under [Pandoc's Markdown],
-can be disabled using the `markdown_strict` format.
+[definition lists], [metadata blocks], [footnotes], [citations], [math],
+and much more.  See below under [Pandoc's Markdown].
 
 Pandoc has a modular design: it consists of a set of readers, which parse
 text in a given format and produce a native representation of the document
-(like an _abstract syntax tree_ or AST), and a set of writers, which convert
+(an _abstract syntax tree_ or AST), and a set of writers, which convert
 this native representation into a target format. Thus, adding an input
 or output format requires only adding a reader or writer. Users can also
 run custom [pandoc filters] to modify the intermediate AST.
@@ -58,56 +40,6 @@
 to be perfect, conversions from formats more expressive than pandoc's
 Markdown can be expected to be lossy.
 
-[Markdown]: http://daringfireball.net/projects/markdown/
-[CommonMark]: http://commonmark.org
-[PHP Markdown Extra]: https://michelf.ca/projects/php-markdown/extra/
-[GitHub-Flavored Markdown]: https://help.github.com/articles/github-flavored-markdown/
-[MultiMarkdown]: http://fletcherpenney.net/multimarkdown/
-[reStructuredText]: http://docutils.sourceforge.net/docs/ref/rst/introduction.html
-[S5]: http://meyerweb.com/eric/tools/s5/
-[Slidy]: http://www.w3.org/Talks/Tools/Slidy/
-[Slideous]: http://goessner.net/articles/slideous/
-[HTML]: http://www.w3.org/html/
-[HTML5]: http://www.w3.org/TR/html5/
-[polyglot markup]: https://www.w3.org/TR/html-polyglot/
-[XHTML]: http://www.w3.org/TR/xhtml1/
-[LaTeX]: http://latex-project.org
-[`beamer`]: https://ctan.org/pkg/beamer
-[Beamer User's Guide]: http://ctan.math.utah.edu/ctan/tex-archive/macros/latex/contrib/beamer/doc/beameruserguide.pdf
-[ConTeXt]: http://www.contextgarden.net/
-[RTF]: http://en.wikipedia.org/wiki/Rich_Text_Format
-[DocBook]: http://docbook.org
-[JATS]: https://jats.nlm.nih.gov
-[txt2tags]: http://txt2tags.org
-[EPUB]: http://idpf.org/epub
-[OPML]: http://dev.opml.org/spec2.html
-[OpenDocument]: http://opendocument.xml.org
-[ODT]: http://en.wikipedia.org/wiki/OpenDocument
-[Textile]: http://redcloth.org/textile
-[MediaWiki markup]: https://www.mediawiki.org/wiki/Help:Formatting
-[DokuWiki markup]: https://www.dokuwiki.org/dokuwiki
-[ZimWiki markup]: http://zim-wiki.org/manual/Help/Wiki_Syntax.html
-[TWiki markup]: http://twiki.org/cgi-bin/view/TWiki/TextFormattingRules
-[TikiWiki markup]: https://doc.tiki.org/Wiki-Syntax-Text#The_Markup_Language_Wiki-Syntax
-[Haddock markup]: https://www.haskell.org/haddock/doc/html/ch03s08.html
-[Creole 1.0]: http://www.wikicreole.org/wiki/Creole1.0
-[groff man]: http://man7.org/linux/man-pages/man7/groff_man.7.html
-[groff ms]: http://man7.org/linux/man-pages/man7/groff_ms.7.html
-[Haskell]: https://www.haskell.org
-[GNU Texinfo]: http://www.gnu.org/software/texinfo/
-[Emacs Org mode]: http://orgmode.org
-[AsciiDoc]: http://www.methods.co.nz/asciidoc/
-[DZSlides]: http://paulrouget.com/dzslides/
-[Word docx]: https://en.wikipedia.org/wiki/Office_Open_XML
-[PDF]: https://www.adobe.com/pdf/
-[reveal.js]: http://lab.hakim.se/reveal-js/
-[FictionBook2]: http://www.fictionbook.org/index.php/Eng:XML_Schema_Fictionbook_2.1
-[InDesign ICML]: http://wwwimages.adobe.com/www.adobe.com/content/dam/acom/en/devnet/indesign/sdk/cs6/idml/idml-cookbook.pdf
-[TEI Simple]: https://github.com/TEIC/TEI-Simple
-[Muse]: https://amusewiki.org/library/manual
-[PowerPoint]: https://en.wikipedia.org/wiki/Microsoft_PowerPoint
-[Vimwiki]: https://vimwiki.github.io
-
 Using `pandoc`
 --------------
 
@@ -283,20 +215,42 @@
 
 `-f` *FORMAT*, `-r` *FORMAT*, `--from=`*FORMAT*, `--read=`*FORMAT*
 
-:   Specify input format.  *FORMAT* can be `native` (native Haskell),
-    `json` (JSON version of native AST), `markdown` (pandoc's
-    extended Markdown), `markdown_strict` (original unextended
-    Markdown), `markdown_phpextra` (PHP Markdown Extra),
-    `markdown_mmd` (MultiMarkdown), `gfm` (GitHub-Flavored Markdown),
-    `commonmark` (CommonMark Markdown), `textile` (Textile), `rst`
-    (reStructuredText), `html` (HTML), `docbook` (DocBook), `t2t`
-    (txt2tags), `docx` (docx), `odt` (ODT), `epub` (EPUB), `opml` (OPML),
-    `org` (Emacs Org mode), `mediawiki` (MediaWiki markup), `twiki` (TWiki
-    markup), `tikiwiki` (TikiWiki markup), `creole` (Creole 1.0),
-    `haddock` (Haddock markup), or `latex` (LaTeX).
-    (`markdown_github` provides deprecated and less accurate support
-    for Github-Flavored Markdown; please use `gfm` instead, unless you
-    need to use extensions other than `smart`.)
+:   Specify input format.  *FORMAT* can be:
+
+    ::: {#input-formats}
+    - `commonmark` ([CommonMark] Markdown)
+    - `creole` ([Creole 1.0])
+    - `docbook` ([DocBook])
+    - `docx` ([Word docx])
+    - `epub` ([EPUB])
+    - `fb2` ([FictionBook2] e-book)
+    - `gfm` ([GitHub-Flavored Markdown]),
+      or `markdown_github`, which provides deprecated and less accurate
+      support for Github-Flavored Markdown; please use `gfm` instead,
+      unless you need to use extensions other than `smart`.
+    - `haddock` ([Haddock markup])
+    - `html` ([HTML])
+    - `jats` ([JATS] XML)
+    - `json` (JSON version of native AST)
+    - `latex` ([LaTeX])
+    - `markdown` ([Pandoc's Markdown])
+    - `markdown_mmd` ([MultiMarkdown])
+    - `markdown_phpextra` ([PHP Markdown Extra])
+    - `markdown_strict` (original unextended [Markdown])
+    - `mediawiki` ([MediaWiki markup])
+    - `muse` ([Muse])
+    - `native` (native Haskell)
+    - `odt` ([ODT])
+    - `opml` ([OPML])
+    - `org` ([Emacs Org mode])
+    - `rst` ([reStructuredText])
+    - `t2t` ([txt2tags])
+    - `textile` ([Textile])
+    - `tikiwiki` ([TikiWiki markup])
+    - `twiki` ([TWiki markup])
+    - `vimwiki` ([Vimwiki])
+    :::
+
     Extensions can be individually enabled or disabled by
     appending `+EXTENSION` or `-EXTENSION` to the format name.
     See [Extensions] below, for a list of extensions and
@@ -305,34 +259,64 @@
 
 `-t` *FORMAT*, `-w` *FORMAT*, `--to=`*FORMAT*, `--write=`*FORMAT*
 
-:   Specify output format.  *FORMAT* can be `native` (native Haskell),
-    `json` (JSON version of native AST), `plain` (plain text),
-    `markdown` (pandoc's extended Markdown), `markdown_strict`
-    (original unextended Markdown), `markdown_phpextra` (PHP Markdown
-    Extra), `markdown_mmd` (MultiMarkdown), `gfm` (GitHub-Flavored
-    Markdown), `commonmark` (CommonMark Markdown), `rst`
-    (reStructuredText), `html4` (XHTML 1.0 Transitional), `html` or
-    `html5` (HTML5/XHTML [polyglot markup]), `latex` (LaTeX), `beamer`
-    (LaTeX beamer slide show), `context` (ConTeXt), `man` (groff man),
-    `mediawiki` (MediaWiki markup), `dokuwiki` (DokuWiki markup),
-    `zimwiki` (ZimWiki markup), `textile` (Textile), `org` (Emacs Org
-    mode), `texinfo` (GNU Texinfo), `opml` (OPML), `docbook` or
-    `docbook4` (DocBook 4), `docbook5` (DocBook 5), `jats` (JATS XML),
-    `opendocument` (OpenDocument), `odt` (OpenOffice text document),
-    `docx` (Word docx), `haddock` (Haddock markup), `rtf` (rich text
-    format), `epub2` (EPUB v2 book), `epub` or `epub3` (EPUB v3),
-    `fb2` (FictionBook2 e-book), `asciidoc` (AsciiDoc), `icml`
-    (InDesign ICML), `tei` (TEI Simple), `slidy` (Slidy HTML and
-    JavaScript slide show), `slideous` (Slideous HTML and JavaScript
-    slide show), `dzslides` (DZSlides HTML5 + JavaScript slide show),
-    `revealjs` (reveal.js HTML5 + JavaScript slide show), `s5` (S5
-    HTML and JavaScript slide show), `pptx` (PowerPoint slide show) or
-    the path of a custom lua writer (see [Custom writers],
-    below). (`markdown_github` provides deprecated and less accurate
-    support for Github-Flavored Markdown; please use `gfm` instead,
-    unless you use extensions that do not work with `gfm`.) Note that
-    `odt`, `docx`, and `epub` output will not be directed to *stdout*
-    unless forced with `-o -`. Extensions can be individually enabled or
+:   Specify output format.  *FORMAT* can be:
+
+    ::: {#output-formats}
+    - `asciidoc` ([AsciiDoc])
+    - `beamer` ([LaTeX beamer][`beamer`] slide show)
+    - `commonmark` ([CommonMark] Markdown)
+    - `context` ([ConTeXt])
+    - `docbook` or `docbook4` ([DocBook] 4)
+    - `docbook5` (DocBook 5)
+    - `docx` ([Word docx])
+    - `dokuwiki` ([DokuWiki markup])
+    - `epub` or `epub3` ([EPUB] v3 book)
+    - `epub2` (EPUB v2)
+    - `fb2` ([FictionBook2] e-book)
+    - `gfm` ([GitHub-Flavored Markdown]),
+      or `markdown_github`, which provides deprecated and less accurate
+      support for Github-Flavored Markdown; please use `gfm` instead,
+      unless you use extensions that do not work with `gfm`.
+    - `haddock` ([Haddock markup])
+    - `html` or `html5` ([HTML], i.e. [HTML5]/XHTML [polyglot markup])
+    - `html4` ([XHTML] 1.0 Transitional)
+    - `icml` ([InDesign ICML])
+    - `jats` ([JATS] XML)
+    - `json` (JSON version of native AST)
+    - `latex` ([LaTeX])
+    - `man` ([groff man])
+    - `markdown` ([Pandoc's Markdown])
+    - `markdown_mmd` ([MultiMarkdown])
+    - `markdown_phpextra` ([PHP Markdown Extra])
+    - `markdown_strict` (original unextended [Markdown])
+    - `mediawiki` ([MediaWiki markup])
+    - `ms` ([groff ms])
+    - `muse` ([Muse]),
+    - `native` (native Haskell),
+    - `odt` ([OpenOffice text document][ODT])
+    - `opml` ([OPML])
+    - `opendocument` ([OpenDocument])
+    - `org` ([Emacs Org mode])
+    - `plain` (plain text),
+    - `pptx` ([PowerPoint] slide show)
+    - `rst` ([reStructuredText])
+    - `rtf` ([Rich Text Format])
+    - `texinfo` ([GNU Texinfo])
+    - `textile` ([Textile])
+    - `slideous` ([Slideous] HTML and JavaScript slide show)
+    - `slidy` ([Slidy] HTML and JavaScript slide show)
+    - `dzslides` ([DZSlides] HTML5 + JavaScript slide show),
+    - `revealjs` ([reveal.js] HTML5 + JavaScript slide show)
+    - `s5` ([S5] HTML and JavaScript slide show)
+    - `tei` ([TEI Simple])
+    - `zimwiki` ([ZimWiki markup])
+    - the path of a custom lua writer, see [Custom writers] below
+    :::
+
+    Note that `odt`, `docx`, and `epub` output will not be directed
+    to *stdout* unless forced with `-o -`.
+
+    Extensions can be individually enabled or
     disabled by appending `+EXTENSION` or `-EXTENSION` to the format
     name.  See [Extensions] below, for a list of extensions and their
     names.  See `--list-output-formats` and `--list-extensions`, below.
@@ -424,6 +408,56 @@
 
 :   Show usage message.
 
+[Markdown]: http://daringfireball.net/projects/markdown/
+[CommonMark]: http://commonmark.org
+[PHP Markdown Extra]: https://michelf.ca/projects/php-markdown/extra/
+[GitHub-Flavored Markdown]: https://help.github.com/articles/github-flavored-markdown/
+[MultiMarkdown]: http://fletcherpenney.net/multimarkdown/
+[reStructuredText]: http://docutils.sourceforge.net/docs/ref/rst/introduction.html
+[S5]: http://meyerweb.com/eric/tools/s5/
+[Slidy]: http://www.w3.org/Talks/Tools/Slidy/
+[Slideous]: http://goessner.net/articles/slideous/
+[HTML]: http://www.w3.org/html/
+[HTML5]: http://www.w3.org/TR/html5/
+[polyglot markup]: https://www.w3.org/TR/html-polyglot/
+[XHTML]: http://www.w3.org/TR/xhtml1/
+[LaTeX]: http://latex-project.org
+[`beamer`]: https://ctan.org/pkg/beamer
+[Beamer User's Guide]: http://ctan.math.utah.edu/ctan/tex-archive/macros/latex/contrib/beamer/doc/beameruserguide.pdf
+[ConTeXt]: http://www.contextgarden.net/
+[Rich Text Format]: http://en.wikipedia.org/wiki/Rich_Text_Format
+[DocBook]: http://docbook.org
+[JATS]: https://jats.nlm.nih.gov
+[txt2tags]: http://txt2tags.org
+[EPUB]: http://idpf.org/epub
+[OPML]: http://dev.opml.org/spec2.html
+[OpenDocument]: http://opendocument.xml.org
+[ODT]: http://en.wikipedia.org/wiki/OpenDocument
+[Textile]: http://redcloth.org/textile
+[MediaWiki markup]: https://www.mediawiki.org/wiki/Help:Formatting
+[DokuWiki markup]: https://www.dokuwiki.org/dokuwiki
+[ZimWiki markup]: http://zim-wiki.org/manual/Help/Wiki_Syntax.html
+[TWiki markup]: http://twiki.org/cgi-bin/view/TWiki/TextFormattingRules
+[TikiWiki markup]: https://doc.tiki.org/Wiki-Syntax-Text#The_Markup_Language_Wiki-Syntax
+[Haddock markup]: https://www.haskell.org/haddock/doc/html/ch03s08.html
+[Creole 1.0]: http://www.wikicreole.org/wiki/Creole1.0
+[groff man]: http://man7.org/linux/man-pages/man7/groff_man.7.html
+[groff ms]: http://man7.org/linux/man-pages/man7/groff_ms.7.html
+[Haskell]: https://www.haskell.org
+[GNU Texinfo]: http://www.gnu.org/software/texinfo/
+[Emacs Org mode]: http://orgmode.org
+[AsciiDoc]: http://www.methods.co.nz/asciidoc/
+[DZSlides]: http://paulrouget.com/dzslides/
+[Word docx]: https://en.wikipedia.org/wiki/Office_Open_XML
+[PDF]: https://www.adobe.com/pdf/
+[reveal.js]: http://lab.hakim.se/reveal-js/
+[FictionBook2]: http://www.fictionbook.org/index.php/Eng:XML_Schema_Fictionbook_2.1
+[InDesign ICML]: http://wwwimages.adobe.com/www.adobe.com/content/dam/acom/en/devnet/indesign/sdk/cs6/idml/idml-cookbook.pdf
+[TEI Simple]: https://github.com/TEIC/TEI-Simple
+[Muse]: https://amusewiki.org/library/manual
+[PowerPoint]: https://en.wikipedia.org/wiki/Microsoft_PowerPoint
+[Vimwiki]: https://vimwiki.github.io
+
 Reader options
 --------------
 
@@ -521,17 +555,27 @@
 
         return {{Str = expand_hello_world}}
 
+    In order of preference, pandoc will look for lua filters in
 
+     1. a specified full or relative path (executable or
+     non-executable)
+
+     2. `$DATADIR/filters` (executable or non-executable)
+     where `$DATADIR` is the user data directory (see
+     `--data-dir`, above).
+
 `-M` *KEY*[`=`*VAL*], `--metadata=`*KEY*[`:`*VAL*]
 
 :   Set the metadata field *KEY* to the value *VAL*.  A value specified
-    on the command line overrides a value specified in the document.
+    on the command line overrides a value specified in the document
+    using [YAML metadata blocks][Extension:`yaml_metadata_block`].
     Values will be parsed as YAML boolean or string values. If no value is
     specified, the value will be treated as Boolean true.  Like
     `--variable`, `--metadata` causes template variables to be set.
     But unlike `--variable`, `--metadata` affects the metadata of the
     underlying document (which is accessible from filters and may be
-    printed in some output formats).
+    printed in some output formats) and metadata values will be escaped
+    when inserted into the template.
 
 `-p`, `--preserve-tabs`
 
@@ -795,9 +839,10 @@
 
 `--ascii`
 
-:   Use only ASCII characters in output.  Currently supported only for
-    HTML and DocBook output (which uses numerical entities instead of
-    UTF-8 when this option is selected).
+:   Use only ASCII characters in output.  Currently supported for
+    XML and HTML formats (which use numerical entities instead of
+    UTF-8 when this option is selected) and for groff ms and man
+    (which use hexadecimal escapes).
 
 `--reference-links`
 
@@ -1171,54 +1216,8 @@
     not specified, a link to the KaTeX CDN will be inserted. Note that this
     option does not imply `--katex`.
 
-`-m` [*URL*], `--latexmathml`[`=`*URL*]
-
-:   *Deprecated.*
-    Use the [LaTeXMathML] script to display embedded TeX math in HTML output.
-    TeX math will be displayed between `$` or `$$` characters and put in
-    `<span>` tags with class `LaTeX`. The LaTeXMathML JavaScript will then
-    change it to MathML. Note that currently only Firefox and Safari
-    (and select e-book readers) natively support MathML.
-    To insert a link the `LaTeXMathML.js` script, provide a *URL*.
-
-`--jsmath`[`=`*URL*]
-
-:   *Deprecated.*
-    Use [jsMath] (the predecessor of MathJax) to display embedded TeX
-    math in HTML output. TeX math will be put inside `<span>` tags
-    (for inline math) or `<div>` tags (for display math) with class
-    `math` and rendered by the jsMath script. The *URL* should point to
-    the script (e.g. `jsMath/easy/load.js`); if provided, it will be linked
-    to in the header of standalone HTML documents. If a *URL* is not provided,
-    no link to the jsMath load script will be inserted; it is then
-    up to the author to provide such a link in the HTML template.
-
-`--gladtex`
-
-:   *Deprecated.*
-    Enclose TeX math in `<eq>` tags in HTML output.  The resulting HTML
-    can then be processed by [gladTeX] to produce images of the typeset
-    formulas and an HTML file with links to these images.
-    So, the procedure is:
-
-        pandoc -s --gladtex input.md -o myfile.htex
-        gladtex -d myfile-images myfile.htex
-        # produces myfile.html and images in myfile-images
-
-`--mimetex`[`=`*URL*]
-
-:   *Deprecated.*
-    Render TeX math using the [mimeTeX] CGI script, which generates an
-    image for each TeX formula. This should work in all browsers. If
-    *URL* is not specified, it is assumed that the script is at
-    `/cgi-bin/mimetex.cgi`.
-
 [MathML]: http://www.w3.org/Math/
-[LaTeXMathML]: http://math.etsu.edu/LaTeXMathML/
-[jsMath]: http://www.math.union.edu/~dpvc/jsmath/
 [MathJax]: https://www.mathjax.org
-[gladTeX]: http://ans.hsh.no/home/mgg/gladtex/
-[mimeTeX]: http://www.forkosh.com/mimetex.html
 [KaTeX]: https://github.com/Khan/KaTeX
 
 Options for wrapper scripts
@@ -1266,23 +1265,22 @@
 - For `pdf` output, customize the `default.latex` template
   (or the `default.context` template, if you use `-t context`,
   or the `default.ms` template, if you use `-t ms`, or the
-  `default.html5` template, if you use `-t html5`).
+  `default.html` template, if you use `-t html`).
 - `docx` has no template (however, you can use
   `--reference-doc` to customize the output).
 
 Templates contain *variables*, which allow for the inclusion of
-arbitrary information at any point in the file. Variables may be set
-within the document using [YAML metadata blocks][Extension:
-`yaml_metadata_block`].  They may also be set at the
-command line using the `-V/--variable` option: variables set in this
-way override metadata fields with the same name.
+arbitrary information at any point in the file. They may be set at the
+command line using the `-V/--variable` option. If a variable is not set,
+pandoc will look for the key in the document's metadata – which can be set
+using either [YAML metadata blocks][Extension:`yaml_metadata_block`]
+or with the `--metadata` option.
 
 Variables set by pandoc
 -----------------------
 
 Some variables are set automatically by pandoc.  These vary somewhat
-depending on the output format, but include metadata fields as well
-as the following:
+depending on the output format, but include the following:
 
 `sourcefile`, `outputfile`
 :   source and destination filenames, as given on the command line.
@@ -1467,6 +1465,9 @@
 :   option for document class, e.g. `oneside`; may be repeated
     for multiple options
 
+`beameroption`
+:   In beamer, add extra beamer option with `\setbeameroption{}`
+
 `geometry`
 :   option for [`geometry`] package, e.g. `margin=1in`;
     may be repeated for multiple options
@@ -1964,9 +1965,9 @@
 writes HTML with the Haskell code in bird tracks, so it can be copied
 and pasted as literate Haskell source.
 
-Note that GHC expects the bird tracks in the first column, so indentend literate
-code blocks (e.g. inside an itemized environment) will not be picked up by the
-Haskell compiler.
+Note that GHC expects the bird tracks in the first column, so indented
+literate code blocks (e.g. inside an itemized environment) will not be
+picked up by the Haskell compiler.
 
 Other extensions
 ----------------
@@ -1982,7 +1983,7 @@
 :  `docx`, `html`
 
 output formats
-:  `markdown`, `docx`, `odt`, `opendocument`, `html`
+:  `docx`, `odt`, `opendocument`, `html`
 
 #### Extension: `styles` #### {#ext-styles}
 
@@ -3096,7 +3097,8 @@
 will be interpreted as markdown. For example:
 
     header-includes:
-    - ```{=latex}
+    - |
+      ```{=latex}
       \let\oldsection\section
       \renewcommand{\section}[1]{\clearpage\oldsection{#1}}
       ```
@@ -3415,9 +3417,24 @@
 
     This is `<a>html</a>`{=html}
 
+This can be useful to insert raw xml into `docx` documents, e.g.
+a pagebreak:
+
+    ```{=openxml}
+    <w:p>
+      <w:r>
+        <w:br w:type="page"/>
+      </w:r>
+    </w:p>
+    ```
+
 The format name should match the target format name (see
 `-t/--to`, above, for a list, or use `pandoc
---list-output-formats`).
+--list-output-formats`). Use `openxml` for `docx` output,
+`opendocument` for `odt` output, `html5` for `epub3` output,
+`html4` for `epub2` output, and `latex`, `beamer`,
+`ms`, or `html5` for `pdf` output (depending on what you
+use for `--pdf-engine`).
 
 This extension presupposes that the relevant kind of
 inline code or fenced code block is enabled.  Thus, for
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -22,93 +22,153 @@
 
 ## The universal markup converter
 
-<div id="description">
+Pandoc is a [Haskell](http://haskell.org) library for converting from
+one markup format to another, and a command-line tool that uses this
+library. It can convert *from*
 
-Pandoc is a [Haskell](https://www.haskell.org) library for converting
-from one markup format to another, and a command-line tool that uses
-this library.
+<div id="input-formats">
 
-Pandoc can read
-[Markdown](http://daringfireball.net/projects/markdown/),
-[CommonMark](http://commonmark.org), [PHP Markdown
-Extra](https://michelf.ca/projects/php-markdown/extra/),
-[GitHub-Flavored
-Markdown](https://help.github.com/articles/github-flavored-markdown/),
-[MultiMarkdown](http://fletcherpenney.net/multimarkdown/), and (subsets
-of) [Textile](http://redcloth.org/textile),
-[reStructuredText](http://docutils.sourceforge.net/docs/ref/rst/introduction.html),
-[HTML](http://www.w3.org/html/), [LaTeX](http://latex-project.org),
-[MediaWiki markup](https://www.mediawiki.org/wiki/Help:Formatting),
-[TWiki markup](http://twiki.org/cgi-bin/view/TWiki/TextFormattingRules),
-[TikiWiki
-markup](https://doc.tiki.org/Wiki-Syntax-Text#The_Markup_Language_Wiki-Syntax),
-[Creole 1.0](http://www.wikicreole.org/wiki/Creole1.0), [Haddock
-markup](https://www.haskell.org/haddock/doc/html/ch03s08.html),
-[OPML](http://dev.opml.org/spec2.html), [Emacs Org
-mode](http://orgmode.org), [DocBook](http://docbook.org),
-[JATS](https://jats.nlm.nih.gov),
-[Muse](https://amusewiki.org/library/manual),
-[txt2tags](http://txt2tags.org), [Vimwiki](https://vimwiki.github.io),
-[EPUB](http://idpf.org/epub),
-[ODT](http://en.wikipedia.org/wiki/OpenDocument), and [Word
-docx](https://en.wikipedia.org/wiki/Office_Open_XML).
+  - `commonmark` ([CommonMark](http://commonmark.org) Markdown)
+  - `creole` ([Creole 1.0](http://www.wikicreole.org/wiki/Creole1.0))
+  - `docbook` ([DocBook](http://docbook.org))
+  - `docx` ([Word docx](https://en.wikipedia.org/wiki/Office_Open_XML))
+  - `epub` ([EPUB](http://idpf.org/epub))
+  - `fb2`
+    ([FictionBook2](http://www.fictionbook.org/index.php/Eng:XML_Schema_Fictionbook_2.1)
+    e-book)
+  - `gfm` ([GitHub-Flavored
+    Markdown](https://help.github.com/articles/github-flavored-markdown/)),
+    or `markdown_github`, which provides deprecated and less accurate
+    support for Github-Flavored Markdown; please use `gfm` instead,
+    unless you need to use extensions other than `smart`.
+  - `haddock` ([Haddock
+    markup](https://www.haskell.org/haddock/doc/html/ch03s08.html))
+  - `html` ([HTML](http://www.w3.org/html/))
+  - `jats` ([JATS](https://jats.nlm.nih.gov) XML)
+  - `json` (JSON version of native AST)
+  - `latex` ([LaTeX](http://latex-project.org))
+  - `markdown` ([Pandoc’s Markdown](#pandocs-markdown))
+  - `markdown_mmd`
+    ([MultiMarkdown](http://fletcherpenney.net/multimarkdown/))
+  - `markdown_phpextra` ([PHP Markdown
+    Extra](https://michelf.ca/projects/php-markdown/extra/))
+  - `markdown_strict` (original unextended
+    [Markdown](http://daringfireball.net/projects/markdown/))
+  - `mediawiki` ([MediaWiki
+    markup](https://www.mediawiki.org/wiki/Help:Formatting))
+  - `muse` ([Muse](https://amusewiki.org/library/manual))
+  - `native` (native Haskell)
+  - `odt` ([ODT](http://en.wikipedia.org/wiki/OpenDocument))
+  - `opml` ([OPML](http://dev.opml.org/spec2.html))
+  - `org` ([Emacs Org mode](http://orgmode.org))
+  - `rst`
+    ([reStructuredText](http://docutils.sourceforge.net/docs/ref/rst/introduction.html))
+  - `t2t` ([txt2tags](http://txt2tags.org))
+  - `textile` ([Textile](http://redcloth.org/textile))
+  - `tikiwiki` ([TikiWiki
+    markup](https://doc.tiki.org/Wiki-Syntax-Text#The_Markup_Language_Wiki-Syntax))
+  - `twiki` ([TWiki
+    markup](http://twiki.org/cgi-bin/view/TWiki/TextFormattingRules))
+  - `vimwiki` ([Vimwiki](https://vimwiki.github.io))
 
-Pandoc can write plain text,
-[Markdown](http://daringfireball.net/projects/markdown/),
-[CommonMark](http://commonmark.org), [PHP Markdown
-Extra](https://michelf.ca/projects/php-markdown/extra/),
-[GitHub-Flavored
-Markdown](https://help.github.com/articles/github-flavored-markdown/),
-[MultiMarkdown](http://fletcherpenney.net/multimarkdown/),
-[reStructuredText](http://docutils.sourceforge.net/docs/ref/rst/introduction.html),
-[XHTML](http://www.w3.org/TR/xhtml1/),
-[HTML5](http://www.w3.org/TR/html5/), [LaTeX](http://latex-project.org)
-(including [`beamer`](https://ctan.org/pkg/beamer) slide shows),
-[ConTeXt](http://www.contextgarden.net/),
-[RTF](http://en.wikipedia.org/wiki/Rich_Text_Format),
-[OPML](http://dev.opml.org/spec2.html), [DocBook](http://docbook.org),
-[JATS](https://jats.nlm.nih.gov),
-[OpenDocument](http://opendocument.xml.org),
-[ODT](http://en.wikipedia.org/wiki/OpenDocument), [Word
-docx](https://en.wikipedia.org/wiki/Office_Open_XML), [GNU
-Texinfo](http://www.gnu.org/software/texinfo/), [MediaWiki
-markup](https://www.mediawiki.org/wiki/Help:Formatting), [DokuWiki
-markup](https://www.dokuwiki.org/dokuwiki), [ZimWiki
-markup](http://zim-wiki.org/manual/Help/Wiki_Syntax.html), [Haddock
-markup](https://www.haskell.org/haddock/doc/html/ch03s08.html),
-[EPUB](http://idpf.org/epub) (v2 or v3),
-[FictionBook2](http://www.fictionbook.org/index.php/Eng:XML_Schema_Fictionbook_2.1),
-[Textile](http://redcloth.org/textile), [groff
-man](http://man7.org/linux/man-pages/man7/groff_man.7.html), [groff
-ms](http://man7.org/linux/man-pages/man7/groff_ms.7.html), [Emacs Org
-mode](http://orgmode.org),
-[AsciiDoc](http://www.methods.co.nz/asciidoc/), [InDesign
-ICML](http://wwwimages.adobe.com/www.adobe.com/content/dam/acom/en/devnet/indesign/sdk/cs6/idml/idml-cookbook.pdf),
-[TEI Simple](https://github.com/TEIC/TEI-Simple),
-[Muse](https://amusewiki.org/library/manual),
-[PowerPoint](https://en.wikipedia.org/wiki/Microsoft_PowerPoint) slide
-shows and [Slidy](http://www.w3.org/Talks/Tools/Slidy/),
-[Slideous](http://goessner.net/articles/slideous/),
-[DZSlides](http://paulrouget.com/dzslides/),
-[reveal.js](http://lab.hakim.se/reveal-js/) or
-[S5](http://meyerweb.com/eric/tools/s5/) HTML slide shows. It can also
-produce [PDF](https://www.adobe.com/pdf/) output on systems where LaTeX,
-ConTeXt, `pdfroff`, `wkhtmltopdf`, `prince`, or `weasyprint` is
-installed.
+</div>
 
+It can convert *to*
+
+<div id="output-formats">
+
+  - `asciidoc` ([AsciiDoc](http://www.methods.co.nz/asciidoc/))
+  - `beamer` ([LaTeX beamer](https://ctan.org/pkg/beamer) slide show)
+  - `commonmark` ([CommonMark](http://commonmark.org) Markdown)
+  - `context` ([ConTeXt](http://www.contextgarden.net/))
+  - `docbook` or `docbook4` ([DocBook](http://docbook.org) 4)
+  - `docbook5` (DocBook 5)
+  - `docx` ([Word docx](https://en.wikipedia.org/wiki/Office_Open_XML))
+  - `dokuwiki` ([DokuWiki markup](https://www.dokuwiki.org/dokuwiki))
+  - `epub` or `epub3` ([EPUB](http://idpf.org/epub) v3 book)
+  - `epub2` (EPUB v2)
+  - `fb2`
+    ([FictionBook2](http://www.fictionbook.org/index.php/Eng:XML_Schema_Fictionbook_2.1)
+    e-book)
+  - `gfm` ([GitHub-Flavored
+    Markdown](https://help.github.com/articles/github-flavored-markdown/)),
+    or `markdown_github`, which provides deprecated and less accurate
+    support for Github-Flavored Markdown; please use `gfm` instead,
+    unless you use extensions that do not work with `gfm`.
+  - `haddock` ([Haddock
+    markup](https://www.haskell.org/haddock/doc/html/ch03s08.html))
+  - `html` or `html5` ([HTML](http://www.w3.org/html/), i.e.
+    [HTML5](http://www.w3.org/TR/html5/)/XHTML [polyglot
+    markup](https://www.w3.org/TR/html-polyglot/))
+  - `html4` ([XHTML](http://www.w3.org/TR/xhtml1/) 1.0 Transitional)
+  - `icml` ([InDesign
+    ICML](http://wwwimages.adobe.com/www.adobe.com/content/dam/acom/en/devnet/indesign/sdk/cs6/idml/idml-cookbook.pdf))
+  - `jats` ([JATS](https://jats.nlm.nih.gov) XML)
+  - `json` (JSON version of native AST)
+  - `latex` ([LaTeX](http://latex-project.org))
+  - `man` ([groff
+    man](http://man7.org/linux/man-pages/man7/groff_man.7.html))
+  - `markdown` ([Pandoc’s Markdown](#pandocs-markdown))
+  - `markdown_mmd`
+    ([MultiMarkdown](http://fletcherpenney.net/multimarkdown/))
+  - `markdown_phpextra` ([PHP Markdown
+    Extra](https://michelf.ca/projects/php-markdown/extra/))
+  - `markdown_strict` (original unextended
+    [Markdown](http://daringfireball.net/projects/markdown/))
+  - `mediawiki` ([MediaWiki
+    markup](https://www.mediawiki.org/wiki/Help:Formatting))
+  - `ms` ([groff
+    ms](http://man7.org/linux/man-pages/man7/groff_ms.7.html))
+  - `muse` ([Muse](https://amusewiki.org/library/manual)),
+  - `native` (native Haskell),
+  - `odt` ([OpenOffice text
+    document](http://en.wikipedia.org/wiki/OpenDocument))
+  - `opml` ([OPML](http://dev.opml.org/spec2.html))
+  - `opendocument` ([OpenDocument](http://opendocument.xml.org))
+  - `org` ([Emacs Org mode](http://orgmode.org))
+  - `plain` (plain text),
+  - `pptx`
+    ([PowerPoint](https://en.wikipedia.org/wiki/Microsoft_PowerPoint)
+    slide show)
+  - `rst`
+    ([reStructuredText](http://docutils.sourceforge.net/docs/ref/rst/introduction.html))
+  - `rtf` ([Rich Text
+    Format](http://en.wikipedia.org/wiki/Rich_Text_Format))
+  - `texinfo` ([GNU Texinfo](http://www.gnu.org/software/texinfo/))
+  - `textile` ([Textile](http://redcloth.org/textile))
+  - `slideous` ([Slideous](http://goessner.net/articles/slideous/) HTML
+    and JavaScript slide show)
+  - `slidy` ([Slidy](http://www.w3.org/Talks/Tools/Slidy/) HTML and
+    JavaScript slide show)
+  - `dzslides` ([DZSlides](http://paulrouget.com/dzslides/) HTML5 +
+    JavaScript slide show),
+  - `revealjs` ([reveal.js](http://lab.hakim.se/reveal-js/) HTML5 +
+    JavaScript slide show)
+  - `s5` ([S5](http://meyerweb.com/eric/tools/s5/) HTML and JavaScript
+    slide show)
+  - `tei` ([TEI Simple](https://github.com/TEIC/TEI-Simple))
+  - `zimwiki` ([ZimWiki
+    markup](http://zim-wiki.org/manual/Help/Wiki_Syntax.html))
+  - the path of a custom lua writer, see [Custom
+    writers](#custom-writers) below
+
+</div>
+
+Pandoc can also produce PDF output via LaTeX, Groff ms, or HTML.
+
 Pandoc’s enhanced version of Markdown includes syntax for tables,
-definition lists, metadata blocks, `Div` blocks, footnotes and
-citations, embedded LaTeX (including math), Markdown inside HTML block
-elements, and much more. These enhancements, described further under
-Pandoc’s Markdown, can be disabled using the `markdown_strict` format.
+definition lists, metadata blocks, footnotes, citations, math, and much
+more. See the User’s Manual below under [Pandoc’s
+Markdown](https://pandoc.org/MANUAL.html#pandocs-markdown).
 
 Pandoc has a modular design: it consists of a set of readers, which
 parse text in a given format and produce a native representation of the
-document (like an *abstract syntax tree* or AST), and a set of writers,
-which convert this native representation into a target format. Thus,
-adding an input or output format requires only adding a reader or
-writer. Users can also run custom [pandoc
-filters](http://pandoc.org/filters.html) to modify the intermediate AST.
+document (an *abstract syntax tree* or AST), and a set of writers, which
+convert this native representation into a target format. Thus, adding an
+input or output format requires only adding a reader or writer. Users
+can also run custom pandoc filters to modify the intermediate AST (see
+the documentation for [filters](https://pandoc.org/filters.html) and
+[lua filters](https://pandoc.org/lua-filters.html)).
 
 Because pandoc’s intermediate representation of a document is less
 expressive than many of the formats it converts between, one should not
@@ -119,8 +179,6 @@
 While conversions from pandoc’s Markdown to all formats aspire to be
 perfect, conversions from formats more expressive than pandoc’s Markdown
 can be expected to be lossy.
-
-</div>
 
 ## Installing
 
diff --git a/changelog b/changelog
--- a/changelog
+++ b/changelog
@@ -1,3 +1,286 @@
+pandoc (2.2)
+
+  * New input format: `fb2` (FictionBook2) (Alexander Krotov).
+
+  * Make `--ascii` work for all XML formats (ICML, OPML, JATS,...),
+    and for `ms` and `man`.
+
+  * Remove deprecated `--latexmathml`, `--gladtex`, `--mimetex`, `--jsmath`, `-m`,
+    `--asciimathml` options.
+
+  * New module Text.Pandoc.Readers.FB2, exporting readFB2 (Alexander
+    Krotov, API change).
+
+  * Markdown reader:
+
+    + Allow empty key-value attributes, like `title=""` (#2944).
+    + Handle table w/o following blank line in fenced div (#4560).
+    + Remove "fallback" for `doubleQuote` parser.  Previously the
+      parser tried to be efficient -- if no end double quote was found,
+      it would just return the contents.  But this could backfire in a
+      case `**this should "be bold**`, since the fallback would return
+      the content `"be bold**` and the closing boldface delimiter
+      would never be encountered.
+    + Improve computation of the relative width of the last column in a
+      multiline table, so we can round-trip tables without constantly
+      shrinking the last column.
+
+  * EPUB reader:
+
+    + Fix images with space in file path (#4344).
+
+  * LaTeX reader:
+
+    + Properly resolve section numbers with `\ref` and chapters (#4529).
+    + Parse sloppypar environment (#4517, Marc Schreiber).
+    + Improve handling of raw LaTeX (for markdown etc.) (#4589, #4594).
+      Previously there were some bugs in how macros were handled.
+    + Support `\MakeUppercase`, `\MakeLowercase', `\uppercase`, `\lowercase`,
+      and also `\MakeTextUppercase` and `\MakeTextLowercase` from textcase
+      (#4959).
+
+  * Textile reader:
+
+    + Fixed tables with no body rows (#4513).
+      Previously these raised an exception.
+
+  * Mediawiki reader:
+
+    + Improve table parsing (#4508).  This fixes detection of table
+      attributes and also handles `!` characters in cells.
+
+  * DocBook reader:
+
+    + Properly handle title in `section` element (#4526).
+      Previously we just got `section_title` for `section` (though `sect1`,
+      `sect2`, etc. were handled properly).
+    + Read tex math as output by asciidoctor (#4569, Joe Hermaszewski).
+
+  * Docx reader:
+
+    + Combine adjacent CodeBlocks with the same attributes into
+      a single CodeBlock.  This prevents a multiline codeblock in
+      Word from being read as different paragraphs.
+
+  * RST reader:
+
+    + Allow < 3 spaces indent under directives (#4579).
+    + Fix anonymous redirects with backticks (#4598).
+
+  * Muse reader (Alexander Krotov):
+
+    + Add support for Text::Amuse multiline headings.
+    + Add `<math>` tag support.
+    + Add support for `<biblio>` and `<play>` tags.
+    + Allow links to have empty descriptions.
+    + Require block `<literal>` tags to be on separate lines.
+    + Allow `-` in anchors.
+    + Allow verse to be indented.
+    + Allow nested footnotes.
+    + Internal improvements.
+
+  * Muse writer (Alexander Krotov):
+
+    + Escape `>` only at the beginning of a line.
+    + Escape `]` in image title.
+    + Escape `]` brackets in URLs as `%5D`.
+    + Only escape brackets when necessary.
+    + Escape ordered list markers.
+    + Do not escape list markers unless preceded by space.
+    + Escape strings starting with space.
+    + Escape semicolons and markers after line break.
+    + Escape `;` to avoid accidental comments.
+    + Don't break headers, line blocks and tables with line breaks.
+    + Correctly output empty headings.
+    + Escape horizontal rule only if at the beginning of the line.
+    + Escape definition list terms starting with list markers.
+    + Place header IDs before header.
+    + Improve span writing.
+    + Do not join Spans in normalization.
+    + Don't align ordered list items.
+    + Remove key-value pairs from attributes before normalization.
+    + Enable `--wrap=preserve` for all tests by default.
+    + Reduced `<verbatim>` tags in output.
+    + Internal changes.
+
+  * RST writer:
+
+    + Use more consistent indentation (#4563).  Previously we
+      used an odd mix of 3- and 4-space indentation.  Now we use 3-space
+      indentation, except for ordered lists, where indentation must
+      depend on the width of the list marker.
+    + Flatten nested inlines (#4368, Francesco Occhipinti).
+      Nested inlines are not valid RST syntax, so we flatten them following
+      some readability criteria discussed in #4368.
+
+  * EPUB writer:
+
+    + Ensure that `pagetitle` is always set, even when structured titles
+      are used.  This prevents spurious warnings about empty title
+      elements (#4486).
+
+  * FB2 writer (Alexander Krotov):
+
+    + Output links inline instead of producing notes.  Previously all links
+      were turned into footnotes with unclickable URLs inside.
+    + Allow emphasis and notes in titles.
+    + Don't intersperse paragraph with empty lines.
+    + Convert metadata value `abstract` to book annotation.
+    + Use `<empty-line />` for `HorizontalRule' rather than `LineBreak`.
+      FB2 does not have a way to represent line breaks inside paragraphs;
+      previously we used `<empty-line />` elements, but these are not allowed
+      inside paragraphs.
+
+  * Powerpoint writer (Jesse Rosenthal):
+
+    + Handle Quoted Inlines (#4532).
+    + Simplify code with `ParseXml`.
+    + Allow fallback options when looking for placeholder type.
+    + Check reference-doc for all layouts.
+    + Simplify speaker notes logic.
+    + Change notes state to a simpler per-slide value.
+    + Remove `Maybe` from `SpeakerNotes` in `Slide`. `mempty`
+      means no speaker notes.
+    + Add tests for improved speaker notes.
+    + Handle speaker notes earlier in the conversion process.
+    + Keep notes with related blocks (#4477).  Some blocks automatically
+      split slides (imgs, tables, `column` divs). We assume that any
+      speaker notes immediately following these are connected to these
+      elements, and keep them with the related blocks, splitting after them.
+    + Remove `docProps/thumbnail.jpeg` in data dir (Jesse Rosenthal, #4588).
+      It contained a nonfree ICC color calibration profile and is not needed
+      for production of a powerpoint document.
+
+  * Markdown writer:
+
+    + Include a blank line at the end of the row in a single-row multiline
+      table, to prevent it from being interpreted as a simple table (#4578).
+
+  * CommonMark writer:
+
+    + Correctly ignore LaTeX raw blocks when `raw_tex` is not
+      enabled (#4527, quasicomputational).
+
+  * EPUB writer:
+
+    + Add `epub:type="footnotes"` to notes section in EPUB3 (#4489).
+
+  * LaTeX writer:
+
+    + In beamer, don't use format specifier for default ordered lists
+      (#4556).  This gives better results for styles that put ordered list
+      markers in boxes or circles.
+    + Update `\lstinline` delimiters (#4369, Tim Parenti).
+
+  * Ms writer:
+
+    + Use `\f[R]` rather than `\f[]` to reset font (#4552).
+    + Use `\f[BI]` and `\f[CB]` in headers, instead of `\f[I]` and `\f[C]`,
+      since the header font is automatically bold (#4552).
+    + Use `\f[CB]` rather than `\f[BC]` for monospace bold (#4552).
+    + Create pdf anchor for a Div with an identifier (#4515).
+    + Escape `/` character in anchor ids (#4515).
+    + Improve escaping for anchor ids: we now use _uNNN_ instead of uNNN
+      to avoid ambiguity.
+
+  * Man writer:
+
+    + Don't escape U+2019 as `'` (#4550).
+
+  * Text.Pandoc.Options:
+
+    + Removed `JsMath`, `LaTeXMathML`, and `GladTeX` constructors from
+    `Text.Pandoc.Options.HTMLMathMethod` [API change].
+
+  * Text.Pandoc.Class:
+
+    + `writeMedia`: unescape URI-escaping in file path.  This avoids
+      writing things like `file%20one.png` to the file system.
+
+  * Text.Pandoc.Parsing:
+
+    + Fix `romanNumeral` parser (#4480).  We previously accepted 'DDC'
+      as 1100.
+    + `uri`: don't treat `*` characters at end as part of URI (#4561).
+
+  * Text.Pandoc.MIME:
+
+    + Use the alias `application/eps` for EPS (#2067).
+      This will ensure that we retain the eps extension after reading the
+      image into a mediabag and writing it again.
+
+  * Text.Pandoc.PDF:
+
+    + Use `withTempDir` in `html2pdf`.
+    + With `xelatex`, don't compress images til the last run (#4484).
+      This saves time for image-heavy documents.
+    + Don't try to convert EPS files (#2067).  `pdflatex converts them
+      itself, and JuicyPixels can't do it.
+    + For `pdflatex`, use a temp directory in the working directory.
+      Otherwise we can have problems with the EPS conversion pdflatex
+      tries to do, which can't operate on a file above the working
+      directory without `--shell-escape`.
+
+  * Changes to tests to accommodate changes in pandoc-types.
+    In <https://github.com/jgm/pandoc-types/pull/36> we changed
+    the table builder to pad cells.  This commit changes tests
+    (and two readers) to accord with this behavior.
+
+  * Set default extensions for `beamer` same as `latex`.
+
+  * LaTeX template:
+
+    + Add `beameroption` variable (#4359, Étienne Bersac).
+    + Use `pgfpages` package; this is needed for notes on second
+      screen in beamer (Étienne Bersac).
+    + Add `background-image` variable (#4601, John Muccigrosso).
+
+  * reveal.js template: Add `background-image` variable (#4600,
+    John Muccigrosso).
+
+  * ms template: Fix date.  Previously `.ND` was used, but this only
+    works if you have a title page, which we don't.  Thanks to @teoric.
+
+  * Removed pragmas for unused extensions (#4506, Anabra).
+
+  * Fix bash completion for `--print-default-data-file` (#4549).
+    Previously this looked in the filesystem, even if pandoc
+    was compiled with `embed_data_files` (and sometimes it looked
+    in a nonexistent build directory).  Now the bash completion
+    script just includes a hard-coded list of data file names.
+
+  * MANUAL:
+
+    + Clarify template vs metadata variables (#4501, Mauro Bieg).
+    + Fix raw content example (#4479, Mauro Bieg).
+    + Specify that you use html for raw output in epub.
+    + Add examples for raw docx blocks (#4472, Tristan Stenner).
+      The documentation states that the target format name should match
+      the output format, which isn't the case for `docx`/`openxml` and
+      some others.
+    + Don't say that `empty_paragraphs` affects markdown output (#4540).
+    + Consolidate input/output format documentation (#4577, Mauro Bieg).
+
+  * New README template. Take in/out formats from manual.
+
+  * Fix example in lua-filters docs (#4459, HeirOfNorton).
+
+  * Use the `-threaded` GHC flag when building benchmarks (#4587,
+    Francesco Occhipinti).
+
+  * Bump temporary upper bound to 1.4.
+
+  * Use pandoc-citeproc 0.14.3.1.
+
+  * Use texmath-0.10.1.2 (fixes escapes in math in ms, #4597).
+
+  * Removed old lib directory.  This was used for something long ago,
+    but plays no role now.
+
+  * Removed unneeded data file `LaTeXMathML.js`.
+
+  * Create 64- and 32-bit versions of Windows binary packages.
+
 pandoc (2.1.3)
 
   * Docx reader (Jesse Rosenthal):
@@ -18,11 +301,14 @@
 
   * Muse reader (Alexander Krotov):
 
-    + Various internal improvements.
     + Require closing tag to have the same indentation as opening.
     + Do not reparse blocks inside unclosed block tag (#4425).
     + Parse `<class>` tag (supported by Emacs Muse).
     + Do not produce empty Str element for unindented verse lines.
+    + Don't allow footnote references inside links.
+    + Allow URL to be empty.
+    + Require that comment semicolons are in the first column (#4551).
+    + Various internal improvements.
 
   * LaTeX reader:
 
diff --git a/data/LaTeXMathML.js b/data/LaTeXMathML.js
deleted file mode 100644
--- a/data/LaTeXMathML.js
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
-LaTeXMathML.js from http://math.etsu.edu/LaTeXMathML/
-Adapted by Jeff Knisely and Douglas Woodall from ASCIIMathML.js v. 1.4.7,
-(c) 2005 Peter Jipsen http://www.chapman.edu/~jipsen.
-Released under the GNU General Public License version 2 or later.
-See the GNU General Public License (at http://www.gnu.org/copyleft/gpl.html)
-for more details.
-*/
-var checkForMathML=true;var notifyIfNoMathML=true;var alertIfNoMathML=false;var mathcolor="";var mathfontfamily="";var showasciiformulaonhover=true;var isIE=document.createElementNS==null;if(document.getElementById==null)
-alert("This webpage requires a recent browser such as \nMozilla/Netscape 7+ or Internet Explorer 6+MathPlayer")
-function AMcreateElementXHTML(t){if(isIE)return document.createElement(t);else return document.createElementNS("http://www.w3.org/1999/xhtml",t);}
-function AMnoMathMLNote(){var nd=AMcreateElementXHTML("h3");nd.setAttribute("align","center")
-nd.appendChild(AMcreateElementXHTML("p"));nd.appendChild(document.createTextNode("To view the "));var an=AMcreateElementXHTML("a");an.appendChild(document.createTextNode("LaTeXMathML"));an.setAttribute("href","http://www.maths.nott.ac.uk/personal/drw/lm.html");nd.appendChild(an);nd.appendChild(document.createTextNode(" notation use Internet Explorer 6+"));an=AMcreateElementXHTML("a");an.appendChild(document.createTextNode("MathPlayer"));an.setAttribute("href","http://www.dessci.com/en/products/mathplayer/download.htm");nd.appendChild(an);nd.appendChild(document.createTextNode(" or Netscape/Mozilla/Firefox"));nd.appendChild(AMcreateElementXHTML("p"));return nd;}
-function AMisMathMLavailable(){if(navigator.appName.slice(0,8)=="Netscape")
-if(navigator.appVersion.slice(0,1)>="5")return null;else return AMnoMathMLNote();else if(navigator.appName.slice(0,9)=="Microsoft")
-try{var ActiveX=new ActiveXObject("MathPlayer.Factory.1");return null;}catch(e){return AMnoMathMLNote();}
-else return AMnoMathMLNote();}
-var AMcal=[0xEF35,0x212C,0xEF36,0xEF37,0x2130,0x2131,0xEF38,0x210B,0x2110,0xEF39,0xEF3A,0x2112,0x2133,0xEF3B,0xEF3C,0xEF3D,0xEF3E,0x211B,0xEF3F,0xEF40,0xEF41,0xEF42,0xEF43,0xEF44,0xEF45,0xEF46];var AMfrk=[0xEF5D,0xEF5E,0x212D,0xEF5F,0xEF60,0xEF61,0xEF62,0x210C,0x2111,0xEF63,0xEF64,0xEF65,0xEF66,0xEF67,0xEF68,0xEF69,0xEF6A,0x211C,0xEF6B,0xEF6C,0xEF6D,0xEF6E,0xEF6F,0xEF70,0xEF71,0x2128];var AMbbb=[0xEF8C,0xEF8D,0x2102,0xEF8E,0xEF8F,0xEF90,0xEF91,0x210D,0xEF92,0xEF93,0xEF94,0xEF95,0xEF96,0x2115,0xEF97,0x2119,0x211A,0x211D,0xEF98,0xEF99,0xEF9A,0xEF9B,0xEF9C,0xEF9D,0xEF9E,0x2124];var CONST=0,UNARY=1,BINARY=2,INFIX=3,LEFTBRACKET=4,RIGHTBRACKET=5,SPACE=6,UNDEROVER=7,DEFINITION=8,TEXT=9,BIG=10,LONG=11,STRETCHY=12,MATRIX=13;var AMsqrt={input:"\\sqrt",tag:"msqrt",output:"sqrt",ttype:UNARY},AMroot={input:"\\root",tag:"mroot",output:"root",ttype:BINARY},AMfrac={input:"\\frac",tag:"mfrac",output:"/",ttype:BINARY},AMover={input:"\\stackrel",tag:"mover",output:"stackrel",ttype:BINARY},AMatop={input:"\\atop",tag:"mfrac",output:"",ttype:INFIX},AMchoose={input:"\\choose",tag:"mfrac",output:"",ttype:INFIX},AMsub={input:"_",tag:"msub",output:"_",ttype:INFIX},AMsup={input:"^",tag:"msup",output:"^",ttype:INFIX},AMtext={input:"\\mathrm",tag:"mtext",output:"text",ttype:TEXT},AMmbox={input:"\\mbox",tag:"mtext",output:"mbox",ttype:TEXT};var AMsymbols=[{input:"\\alpha",tag:"mi",output:"\u03B1",ttype:CONST},{input:"\\beta",tag:"mi",output:"\u03B2",ttype:CONST},{input:"\\gamma",tag:"mi",output:"\u03B3",ttype:CONST},{input:"\\delta",tag:"mi",output:"\u03B4",ttype:CONST},{input:"\\epsilon",tag:"mi",output:"\u03B5",ttype:CONST},{input:"\\varepsilon",tag:"mi",output:"\u025B",ttype:CONST},{input:"\\zeta",tag:"mi",output:"\u03B6",ttype:CONST},{input:"\\eta",tag:"mi",output:"\u03B7",ttype:CONST},{input:"\\theta",tag:"mi",output:"\u03B8",ttype:CONST},{input:"\\vartheta",tag:"mi",output:"\u03D1",ttype:CONST},{input:"\\iota",tag:"mi",output:"\u03B9",ttype:CONST},{input:"\\kappa",tag:"mi",output:"\u03BA",ttype:CONST},{input:"\\lambda",tag:"mi",output:"\u03BB",ttype:CONST},{input:"\\mu",tag:"mi",output:"\u03BC",ttype:CONST},{input:"\\nu",tag:"mi",output:"\u03BD",ttype:CONST},{input:"\\xi",tag:"mi",output:"\u03BE",ttype:CONST},{input:"\\pi",tag:"mi",output:"\u03C0",ttype:CONST},{input:"\\varpi",tag:"mi",output:"\u03D6",ttype:CONST},{input:"\\rho",tag:"mi",output:"\u03C1",ttype:CONST},{input:"\\varrho",tag:"mi",output:"\u03F1",ttype:CONST},{input:"\\varsigma",tag:"mi",output:"\u03C2",ttype:CONST},{input:"\\sigma",tag:"mi",output:"\u03C3",ttype:CONST},{input:"\\tau",tag:"mi",output:"\u03C4",ttype:CONST},{input:"\\upsilon",tag:"mi",output:"\u03C5",ttype:CONST},{input:"\\phi",tag:"mi",output:"\u03C6",ttype:CONST},{input:"\\varphi",tag:"mi",output:"\u03D5",ttype:CONST},{input:"\\chi",tag:"mi",output:"\u03C7",ttype:CONST},{input:"\\psi",tag:"mi",output:"\u03C8",ttype:CONST},{input:"\\omega",tag:"mi",output:"\u03C9",ttype:CONST},{input:"\\Gamma",tag:"mo",output:"\u0393",ttype:CONST},{input:"\\Delta",tag:"mo",output:"\u0394",ttype:CONST},{input:"\\Theta",tag:"mo",output:"\u0398",ttype:CONST},{input:"\\Lambda",tag:"mo",output:"\u039B",ttype:CONST},{input:"\\Xi",tag:"mo",output:"\u039E",ttype:CONST},{input:"\\Pi",tag:"mo",output:"\u03A0",ttype:CONST},{input:"\\Sigma",tag:"mo",output:"\u03A3",ttype:CONST},{input:"\\Upsilon",tag:"mo",output:"\u03A5",ttype:CONST},{input:"\\Phi",tag:"mo",output:"\u03A6",ttype:CONST},{input:"\\Psi",tag:"mo",output:"\u03A8",ttype:CONST},{input:"\\Omega",tag:"mo",output:"\u03A9",ttype:CONST},{input:"\\frac12",tag:"mo",output:"\u00BD",ttype:CONST},{input:"\\frac14",tag:"mo",output:"\u00BC",ttype:CONST},{input:"\\frac34",tag:"mo",output:"\u00BE",ttype:CONST},{input:"\\frac13",tag:"mo",output:"\u2153",ttype:CONST},{input:"\\frac23",tag:"mo",output:"\u2154",ttype:CONST},{input:"\\frac15",tag:"mo",output:"\u2155",ttype:CONST},{input:"\\frac25",tag:"mo",output:"\u2156",ttype:CONST},{input:"\\frac35",tag:"mo",output:"\u2157",ttype:CONST},{input:"\\frac45",tag:"mo",output:"\u2158",ttype:CONST},{input:"\\frac16",tag:"mo",output:"\u2159",ttype:CONST},{input:"\\frac56",tag:"mo",output:"\u215A",ttype:CONST},{input:"\\frac18",tag:"mo",output:"\u215B",ttype:CONST},{input:"\\frac38",tag:"mo",output:"\u215C",ttype:CONST},{input:"\\frac58",tag:"mo",output:"\u215D",ttype:CONST},{input:"\\frac78",tag:"mo",output:"\u215E",ttype:CONST},{input:"\\pm",tag:"mo",output:"\u00B1",ttype:CONST},{input:"\\mp",tag:"mo",output:"\u2213",ttype:CONST},{input:"\\triangleleft",tag:"mo",output:"\u22B2",ttype:CONST},{input:"\\triangleright",tag:"mo",output:"\u22B3",ttype:CONST},{input:"\\cdot",tag:"mo",output:"\u22C5",ttype:CONST},{input:"\\star",tag:"mo",output:"\u22C6",ttype:CONST},{input:"\\ast",tag:"mo",output:"\u002A",ttype:CONST},{input:"\\times",tag:"mo",output:"\u00D7",ttype:CONST},{input:"\\div",tag:"mo",output:"\u00F7",ttype:CONST},{input:"\\circ",tag:"mo",output:"\u2218",ttype:CONST},{input:"\\bullet",tag:"mo",output:"\u2022",ttype:CONST},{input:"\\oplus",tag:"mo",output:"\u2295",ttype:CONST},{input:"\\ominus",tag:"mo",output:"\u2296",ttype:CONST},{input:"\\otimes",tag:"mo",output:"\u2297",ttype:CONST},{input:"\\bigcirc",tag:"mo",output:"\u25CB",ttype:CONST},{input:"\\oslash",tag:"mo",output:"\u2298",ttype:CONST},{input:"\\odot",tag:"mo",output:"\u2299",ttype:CONST},{input:"\\land",tag:"mo",output:"\u2227",ttype:CONST},{input:"\\wedge",tag:"mo",output:"\u2227",ttype:CONST},{input:"\\lor",tag:"mo",output:"\u2228",ttype:CONST},{input:"\\vee",tag:"mo",output:"\u2228",ttype:CONST},{input:"\\cap",tag:"mo",output:"\u2229",ttype:CONST},{input:"\\cup",tag:"mo",output:"\u222A",ttype:CONST},{input:"\\sqcap",tag:"mo",output:"\u2293",ttype:CONST},{input:"\\sqcup",tag:"mo",output:"\u2294",ttype:CONST},{input:"\\uplus",tag:"mo",output:"\u228E",ttype:CONST},{input:"\\amalg",tag:"mo",output:"\u2210",ttype:CONST},{input:"\\bigtriangleup",tag:"mo",output:"\u25B3",ttype:CONST},{input:"\\bigtriangledown",tag:"mo",output:"\u25BD",ttype:CONST},{input:"\\dag",tag:"mo",output:"\u2020",ttype:CONST},{input:"\\dagger",tag:"mo",output:"\u2020",ttype:CONST},{input:"\\ddag",tag:"mo",output:"\u2021",ttype:CONST},{input:"\\ddagger",tag:"mo",output:"\u2021",ttype:CONST},{input:"\\lhd",tag:"mo",output:"\u22B2",ttype:CONST},{input:"\\rhd",tag:"mo",output:"\u22B3",ttype:CONST},{input:"\\unlhd",tag:"mo",output:"\u22B4",ttype:CONST},{input:"\\unrhd",tag:"mo",output:"\u22B5",ttype:CONST},{input:"\\sum",tag:"mo",output:"\u2211",ttype:UNDEROVER},{input:"\\prod",tag:"mo",output:"\u220F",ttype:UNDEROVER},{input:"\\bigcap",tag:"mo",output:"\u22C2",ttype:UNDEROVER},{input:"\\bigcup",tag:"mo",output:"\u22C3",ttype:UNDEROVER},{input:"\\bigwedge",tag:"mo",output:"\u22C0",ttype:UNDEROVER},{input:"\\bigvee",tag:"mo",output:"\u22C1",ttype:UNDEROVER},{input:"\\bigsqcap",tag:"mo",output:"\u2A05",ttype:UNDEROVER},{input:"\\bigsqcup",tag:"mo",output:"\u2A06",ttype:UNDEROVER},{input:"\\coprod",tag:"mo",output:"\u2210",ttype:UNDEROVER},{input:"\\bigoplus",tag:"mo",output:"\u2A01",ttype:UNDEROVER},{input:"\\bigotimes",tag:"mo",output:"\u2A02",ttype:UNDEROVER},{input:"\\bigodot",tag:"mo",output:"\u2A00",ttype:UNDEROVER},{input:"\\biguplus",tag:"mo",output:"\u2A04",ttype:UNDEROVER},{input:"\\int",tag:"mo",output:"\u222B",ttype:CONST},{input:"\\oint",tag:"mo",output:"\u222E",ttype:CONST},{input:":=",tag:"mo",output:":=",ttype:CONST},{input:"\\lt",tag:"mo",output:"<",ttype:CONST},{input:"\\gt",tag:"mo",output:">",ttype:CONST},{input:"\\ne",tag:"mo",output:"\u2260",ttype:CONST},{input:"\\neq",tag:"mo",output:"\u2260",ttype:CONST},{input:"\\le",tag:"mo",output:"\u2264",ttype:CONST},{input:"\\leq",tag:"mo",output:"\u2264",ttype:CONST},{input:"\\leqslant",tag:"mo",output:"\u2264",ttype:CONST},{input:"\\ge",tag:"mo",output:"\u2265",ttype:CONST},{input:"\\geq",tag:"mo",output:"\u2265",ttype:CONST},{input:"\\geqslant",tag:"mo",output:"\u2265",ttype:CONST},{input:"\\equiv",tag:"mo",output:"\u2261",ttype:CONST},{input:"\\ll",tag:"mo",output:"\u226A",ttype:CONST},{input:"\\gg",tag:"mo",output:"\u226B",ttype:CONST},{input:"\\doteq",tag:"mo",output:"\u2250",ttype:CONST},{input:"\\prec",tag:"mo",output:"\u227A",ttype:CONST},{input:"\\succ",tag:"mo",output:"\u227B",ttype:CONST},{input:"\\preceq",tag:"mo",output:"\u227C",ttype:CONST},{input:"\\succeq",tag:"mo",output:"\u227D",ttype:CONST},{input:"\\subset",tag:"mo",output:"\u2282",ttype:CONST},{input:"\\supset",tag:"mo",output:"\u2283",ttype:CONST},{input:"\\subseteq",tag:"mo",output:"\u2286",ttype:CONST},{input:"\\supseteq",tag:"mo",output:"\u2287",ttype:CONST},{input:"\\sqsubset",tag:"mo",output:"\u228F",ttype:CONST},{input:"\\sqsupset",tag:"mo",output:"\u2290",ttype:CONST},{input:"\\sqsubseteq",tag:"mo",output:"\u2291",ttype:CONST},{input:"\\sqsupseteq",tag:"mo",output:"\u2292",ttype:CONST},{input:"\\sim",tag:"mo",output:"\u223C",ttype:CONST},{input:"\\simeq",tag:"mo",output:"\u2243",ttype:CONST},{input:"\\approx",tag:"mo",output:"\u2248",ttype:CONST},{input:"\\cong",tag:"mo",output:"\u2245",ttype:CONST},{input:"\\Join",tag:"mo",output:"\u22C8",ttype:CONST},{input:"\\bowtie",tag:"mo",output:"\u22C8",ttype:CONST},{input:"\\in",tag:"mo",output:"\u2208",ttype:CONST},{input:"\\ni",tag:"mo",output:"\u220B",ttype:CONST},{input:"\\owns",tag:"mo",output:"\u220B",ttype:CONST},{input:"\\propto",tag:"mo",output:"\u221D",ttype:CONST},{input:"\\vdash",tag:"mo",output:"\u22A2",ttype:CONST},{input:"\\dashv",tag:"mo",output:"\u22A3",ttype:CONST},{input:"\\models",tag:"mo",output:"\u22A8",ttype:CONST},{input:"\\perp",tag:"mo",output:"\u22A5",ttype:CONST},{input:"\\smile",tag:"mo",output:"\u2323",ttype:CONST},{input:"\\frown",tag:"mo",output:"\u2322",ttype:CONST},{input:"\\asymp",tag:"mo",output:"\u224D",ttype:CONST},{input:"\\notin",tag:"mo",output:"\u2209",ttype:CONST},{input:"\\begin{eqnarray}",output:"X",ttype:MATRIX,invisible:true},{input:"\\begin{array}",output:"X",ttype:MATRIX,invisible:true},{input:"\\\\",output:"}&{",ttype:DEFINITION},{input:"\\end{eqnarray}",output:"}}",ttype:DEFINITION},{input:"\\end{array}",output:"}}",ttype:DEFINITION},{input:"\\big",tag:"mo",output:"X",atval:"1.2",ieval:"2.2",ttype:BIG},{input:"\\Big",tag:"mo",output:"X",atval:"1.6",ieval:"2.6",ttype:BIG},{input:"\\bigg",tag:"mo",output:"X",atval:"2.2",ieval:"3.2",ttype:BIG},{input:"\\Bigg",tag:"mo",output:"X",atval:"2.9",ieval:"3.9",ttype:BIG},{input:"\\left",tag:"mo",output:"X",ttype:LEFTBRACKET},{input:"\\right",tag:"mo",output:"X",ttype:RIGHTBRACKET},{input:"{",output:"{",ttype:LEFTBRACKET,invisible:true},{input:"}",output:"}",ttype:RIGHTBRACKET,invisible:true},{input:"(",tag:"mo",output:"(",atval:"1",ttype:STRETCHY},{input:"[",tag:"mo",output:"[",atval:"1",ttype:STRETCHY},{input:"\\lbrack",tag:"mo",output:"[",atval:"1",ttype:STRETCHY},{input:"\\{",tag:"mo",output:"{",atval:"1",ttype:STRETCHY},{input:"\\lbrace",tag:"mo",output:"{",atval:"1",ttype:STRETCHY},{input:"\\langle",tag:"mo",output:"\u2329",atval:"1",ttype:STRETCHY},{input:"\\lfloor",tag:"mo",output:"\u230A",atval:"1",ttype:STRETCHY},{input:"\\lceil",tag:"mo",output:"\u2308",atval:"1",ttype:STRETCHY},{input:")",tag:"mo",output:")",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"]",tag:"mo",output:"]",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rbrack",tag:"mo",output:"]",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\}",tag:"mo",output:"}",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rbrace",tag:"mo",output:"}",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rangle",tag:"mo",output:"\u232A",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rfloor",tag:"mo",output:"\u230B",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rceil",tag:"mo",output:"\u2309",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"|",tag:"mo",output:"\u2223",atval:"1",ttype:STRETCHY},{input:"\\|",tag:"mo",output:"\u2225",atval:"1",ttype:STRETCHY},{input:"\\vert",tag:"mo",output:"\u2223",atval:"1",ttype:STRETCHY},{input:"\\Vert",tag:"mo",output:"\u2225",atval:"1",ttype:STRETCHY},{input:"\\mid",tag:"mo",output:"\u2223",atval:"1",ttype:STRETCHY},{input:"\\parallel",tag:"mo",output:"\u2225",atval:"1",ttype:STRETCHY},{input:"/",tag:"mo",output:"/",atval:"1.01",ttype:STRETCHY},{input:"\\backslash",tag:"mo",output:"\u2216",atval:"1",ttype:STRETCHY},{input:"\\setminus",tag:"mo",output:"\\",ttype:CONST},{input:"\\!",tag:"mspace",atname:"width",atval:"-0.167em",ttype:SPACE},{input:"\\,",tag:"mspace",atname:"width",atval:"0.167em",ttype:SPACE},{input:"\\>",tag:"mspace",atname:"width",atval:"0.222em",ttype:SPACE},{input:"\\:",tag:"mspace",atname:"width",atval:"0.222em",ttype:SPACE},{input:"\\;",tag:"mspace",atname:"width",atval:"0.278em",ttype:SPACE},{input:"~",tag:"mspace",atname:"width",atval:"0.333em",ttype:SPACE},{input:"\\quad",tag:"mspace",atname:"width",atval:"1em",ttype:SPACE},{input:"\\qquad",tag:"mspace",atname:"width",atval:"2em",ttype:SPACE},{input:"\\prime",tag:"mo",output:"\u2032",ttype:CONST},{input:"'",tag:"mo",output:"\u02B9",ttype:CONST},{input:"''",tag:"mo",output:"\u02BA",ttype:CONST},{input:"'''",tag:"mo",output:"\u2034",ttype:CONST},{input:"''''",tag:"mo",output:"\u2057",ttype:CONST},{input:"\\ldots",tag:"mo",output:"\u2026",ttype:CONST},{input:"\\cdots",tag:"mo",output:"\u22EF",ttype:CONST},{input:"\\vdots",tag:"mo",output:"\u22EE",ttype:CONST},{input:"\\ddots",tag:"mo",output:"\u22F1",ttype:CONST},{input:"\\forall",tag:"mo",output:"\u2200",ttype:CONST},{input:"\\exists",tag:"mo",output:"\u2203",ttype:CONST},{input:"\\Re",tag:"mo",output:"\u211C",ttype:CONST},{input:"\\Im",tag:"mo",output:"\u2111",ttype:CONST},{input:"\\aleph",tag:"mo",output:"\u2135",ttype:CONST},{input:"\\hbar",tag:"mo",output:"\u210F",ttype:CONST},{input:"\\ell",tag:"mo",output:"\u2113",ttype:CONST},{input:"\\wp",tag:"mo",output:"\u2118",ttype:CONST},{input:"\\emptyset",tag:"mo",output:"\u2205",ttype:CONST},{input:"\\infty",tag:"mo",output:"\u221E",ttype:CONST},{input:"\\surd",tag:"mo",output:"\\sqrt{}",ttype:DEFINITION},{input:"\\partial",tag:"mo",output:"\u2202",ttype:CONST},{input:"\\nabla",tag:"mo",output:"\u2207",ttype:CONST},{input:"\\triangle",tag:"mo",output:"\u25B3",ttype:CONST},{input:"\\therefore",tag:"mo",output:"\u2234",ttype:CONST},{input:"\\angle",tag:"mo",output:"\u2220",ttype:CONST},{input:"\\diamond",tag:"mo",output:"\u22C4",ttype:CONST},{input:"\\Diamond",tag:"mo",output:"\u25C7",ttype:CONST},{input:"\\neg",tag:"mo",output:"\u00AC",ttype:CONST},{input:"\\lnot",tag:"mo",output:"\u00AC",ttype:CONST},{input:"\\bot",tag:"mo",output:"\u22A5",ttype:CONST},{input:"\\top",tag:"mo",output:"\u22A4",ttype:CONST},{input:"\\square",tag:"mo",output:"\u25AB",ttype:CONST},{input:"\\Box",tag:"mo",output:"\u25A1",ttype:CONST},{input:"\\wr",tag:"mo",output:"\u2240",ttype:CONST},{input:"\\arccos",tag:"mi",output:"arccos",ttype:UNARY,func:true},{input:"\\arcsin",tag:"mi",output:"arcsin",ttype:UNARY,func:true},{input:"\\arctan",tag:"mi",output:"arctan",ttype:UNARY,func:true},{input:"\\arg",tag:"mi",output:"arg",ttype:UNARY,func:true},{input:"\\cos",tag:"mi",output:"cos",ttype:UNARY,func:true},{input:"\\cosh",tag:"mi",output:"cosh",ttype:UNARY,func:true},{input:"\\cot",tag:"mi",output:"cot",ttype:UNARY,func:true},{input:"\\coth",tag:"mi",output:"coth",ttype:UNARY,func:true},{input:"\\csc",tag:"mi",output:"csc",ttype:UNARY,func:true},{input:"\\deg",tag:"mi",output:"deg",ttype:UNARY,func:true},{input:"\\det",tag:"mi",output:"det",ttype:UNARY,func:true},{input:"\\dim",tag:"mi",output:"dim",ttype:UNARY,func:true},{input:"\\exp",tag:"mi",output:"exp",ttype:UNARY,func:true},{input:"\\gcd",tag:"mi",output:"gcd",ttype:UNARY,func:true},{input:"\\hom",tag:"mi",output:"hom",ttype:UNARY,func:true},{input:"\\inf",tag:"mo",output:"inf",ttype:UNDEROVER},{input:"\\ker",tag:"mi",output:"ker",ttype:UNARY,func:true},{input:"\\lg",tag:"mi",output:"lg",ttype:UNARY,func:true},{input:"\\lim",tag:"mo",output:"lim",ttype:UNDEROVER},{input:"\\liminf",tag:"mo",output:"liminf",ttype:UNDEROVER},{input:"\\limsup",tag:"mo",output:"limsup",ttype:UNDEROVER},{input:"\\ln",tag:"mi",output:"ln",ttype:UNARY,func:true},{input:"\\log",tag:"mi",output:"log",ttype:UNARY,func:true},{input:"\\max",tag:"mo",output:"max",ttype:UNDEROVER},{input:"\\min",tag:"mo",output:"min",ttype:UNDEROVER},{input:"\\Pr",tag:"mi",output:"Pr",ttype:UNARY,func:true},{input:"\\sec",tag:"mi",output:"sec",ttype:UNARY,func:true},{input:"\\sin",tag:"mi",output:"sin",ttype:UNARY,func:true},{input:"\\sinh",tag:"mi",output:"sinh",ttype:UNARY,func:true},{input:"\\sup",tag:"mo",output:"sup",ttype:UNDEROVER},{input:"\\tan",tag:"mi",output:"tan",ttype:UNARY,func:true},{input:"\\tanh",tag:"mi",output:"tanh",ttype:UNARY,func:true},{input:"\\gets",tag:"mo",output:"\u2190",ttype:CONST},{input:"\\leftarrow",tag:"mo",output:"\u2190",ttype:CONST},{input:"\\to",tag:"mo",output:"\u2192",ttype:CONST},{input:"\\rightarrow",tag:"mo",output:"\u2192",ttype:CONST},{input:"\\leftrightarrow",tag:"mo",output:"\u2194",ttype:CONST},{input:"\\uparrow",tag:"mo",output:"\u2191",ttype:CONST},{input:"\\downarrow",tag:"mo",output:"\u2193",ttype:CONST},{input:"\\updownarrow",tag:"mo",output:"\u2195",ttype:CONST},{input:"\\Leftarrow",tag:"mo",output:"\u21D0",ttype:CONST},{input:"\\Rightarrow",tag:"mo",output:"\u21D2",ttype:CONST},{input:"\\Leftrightarrow",tag:"mo",output:"\u21D4",ttype:CONST},{input:"\\iff",tag:"mo",output:"~\\Longleftrightarrow~",ttype:DEFINITION},{input:"\\Uparrow",tag:"mo",output:"\u21D1",ttype:CONST},{input:"\\Downarrow",tag:"mo",output:"\u21D3",ttype:CONST},{input:"\\Updownarrow",tag:"mo",output:"\u21D5",ttype:CONST},{input:"\\mapsto",tag:"mo",output:"\u21A6",ttype:CONST},{input:"\\longleftarrow",tag:"mo",output:"\u2190",ttype:LONG},{input:"\\longrightarrow",tag:"mo",output:"\u2192",ttype:LONG},{input:"\\longleftrightarrow",tag:"mo",output:"\u2194",ttype:LONG},{input:"\\Longleftarrow",tag:"mo",output:"\u21D0",ttype:LONG},{input:"\\Longrightarrow",tag:"mo",output:"\u21D2",ttype:LONG},{input:"\\Longleftrightarrow",tag:"mo",output:"\u21D4",ttype:LONG},{input:"\\longmapsto",tag:"mo",output:"\u21A6",ttype:CONST},AMsqrt,AMroot,AMfrac,AMover,AMsub,AMsup,AMtext,AMmbox,AMatop,AMchoose,{input:"\\acute",tag:"mover",output:"\u00B4",ttype:UNARY,acc:true},{input:"\\grave",tag:"mover",output:"\u0060",ttype:UNARY,acc:true},{input:"\\breve",tag:"mover",output:"\u02D8",ttype:UNARY,acc:true},{input:"\\check",tag:"mover",output:"\u02C7",ttype:UNARY,acc:true},{input:"\\dot",tag:"mover",output:".",ttype:UNARY,acc:true},{input:"\\ddot",tag:"mover",output:"..",ttype:UNARY,acc:true},{input:"\\mathring",tag:"mover",output:"\u00B0",ttype:UNARY,acc:true},{input:"\\vec",tag:"mover",output:"\u20D7",ttype:UNARY,acc:true},{input:"\\overrightarrow",tag:"mover",output:"\u20D7",ttype:UNARY,acc:true},{input:"\\overleftarrow",tag:"mover",output:"\u20D6",ttype:UNARY,acc:true},{input:"\\hat",tag:"mover",output:"\u005E",ttype:UNARY,acc:true},{input:"\\widehat",tag:"mover",output:"\u0302",ttype:UNARY,acc:true},{input:"\\tilde",tag:"mover",output:"~",ttype:UNARY,acc:true},{input:"\\widetilde",tag:"mover",output:"\u02DC",ttype:UNARY,acc:true},{input:"\\bar",tag:"mover",output:"\u203E",ttype:UNARY,acc:true},{input:"\\overbrace",tag:"mover",output:"\uFE37",ttype:UNARY,acc:true},{input:"\\overbracket",tag:"mover",output:"\u23B4",ttype:UNARY,acc:true},{input:"\\overline",tag:"mover",output:"\u00AF",ttype:UNARY,acc:true},{input:"\\underbrace",tag:"munder",output:"\uFE38",ttype:UNARY,acc:true},{input:"\\underbracket",tag:"munder",output:"\u23B5",ttype:UNARY,acc:true},{input:"\\underline",tag:"munder",output:"\u00AF",ttype:UNARY,acc:true},{input:"\\displaystyle",tag:"mstyle",atname:"displaystyle",atval:"true",ttype:UNARY},{input:"\\textstyle",tag:"mstyle",atname:"displaystyle",atval:"false",ttype:UNARY},{input:"\\scriptstyle",tag:"mstyle",atname:"scriptlevel",atval:"1",ttype:UNARY},{input:"\\scriptscriptstyle",tag:"mstyle",atname:"scriptlevel",atval:"2",ttype:UNARY},{input:"\\textrm",tag:"mstyle",output:"\\mathrm",ttype:DEFINITION},{input:"\\mathbf",tag:"mstyle",atname:"mathvariant",atval:"bold",ttype:UNARY},{input:"\\textbf",tag:"mstyle",atname:"mathvariant",atval:"bold",ttype:UNARY},{input:"\\mathit",tag:"mstyle",atname:"mathvariant",atval:"italic",ttype:UNARY},{input:"\\textit",tag:"mstyle",atname:"mathvariant",atval:"italic",ttype:UNARY},{input:"\\mathtt",tag:"mstyle",atname:"mathvariant",atval:"monospace",ttype:UNARY},{input:"\\texttt",tag:"mstyle",atname:"mathvariant",atval:"monospace",ttype:UNARY},{input:"\\mathsf",tag:"mstyle",atname:"mathvariant",atval:"sans-serif",ttype:UNARY},{input:"\\mathbb",tag:"mstyle",atname:"mathvariant",atval:"double-struck",ttype:UNARY,codes:AMbbb},{input:"\\mathcal",tag:"mstyle",atname:"mathvariant",atval:"script",ttype:UNARY,codes:AMcal},{input:"\\mathfrak",tag:"mstyle",atname:"mathvariant",atval:"fraktur",ttype:UNARY,codes:AMfrk},{input:"\\textcolor",tag:"mstyle",atname:"mathvariant",atval:"mathcolor",ttype:BINARY},{input:"\\colorbox",tag:"mstyle",atname:"mathvariant",atval:"background",ttype:BINARY}];function compareNames(s1,s2){if(s1.input>s2.input)return 1
-else return-1;}
-var AMnames=[];function AMinitSymbols(){AMsymbols.sort(compareNames);for(i=0;i<AMsymbols.length;i++)AMnames[i]=AMsymbols[i].input;}
-var AMmathml="http://www.w3.org/1998/Math/MathML";function AMcreateElementMathML(t){if(isIE)return document.createElement("m:"+t);else return document.createElementNS(AMmathml,t);}
-function AMcreateMmlNode(t,frag){if(isIE)var node=document.createElement("m:"+t);else var node=document.createElementNS(AMmathml,t);node.appendChild(frag);return node;}
-function newcommand(oldstr,newstr){AMsymbols=AMsymbols.concat([{input:oldstr,tag:"mo",output:newstr,ttype:DEFINITION}]);}
-function AMremoveCharsAndBlanks(str,n){var st;st=str.slice(n);for(var i=0;i<st.length&&st.charCodeAt(i)<=32;i=i+1);return st.slice(i);}
-function AMposition(arr,str,n){if(n==0){var h,m;n=-1;h=arr.length;while(n+1<h){m=(n+h)>>1;if(arr[m]<str)n=m;else h=m;}
-return h;}else
-for(var i=n;i<arr.length&&arr[i]<str;i++);return i;}
-function AMgetSymbol(str){var k=0;var j=0;var mk;var st;var tagst;var match="";var more=true;for(var i=1;i<=str.length&&more;i++){st=str.slice(0,i);j=k;k=AMposition(AMnames,st,j);if(k<AMnames.length&&str.slice(0,AMnames[k].length)==AMnames[k]){match=AMnames[k];mk=k;i=match.length;}
-more=k<AMnames.length&&str.slice(0,AMnames[k].length)>=AMnames[k];}
-AMpreviousSymbol=AMcurrentSymbol;if(match!=""){AMcurrentSymbol=AMsymbols[mk].ttype;return AMsymbols[mk];}
-AMcurrentSymbol=CONST;k=1;st=str.slice(0,1);if("0"<=st&&st<="9")tagst="mn";else tagst=(("A">st||st>"Z")&&("a">st||st>"z")?"mo":"mi");return{input:st,tag:tagst,output:st,ttype:CONST};}
-var AMpreviousSymbol,AMcurrentSymbol;function AMparseSexpr(str){var symbol,node,result,result2,i,st,newFrag=document.createDocumentFragment();str=AMremoveCharsAndBlanks(str,0);symbol=AMgetSymbol(str);if(symbol==null||symbol.ttype==RIGHTBRACKET)
-return[null,str,null];if(symbol.ttype==DEFINITION){str=symbol.output+AMremoveCharsAndBlanks(str,symbol.input.length);symbol=AMgetSymbol(str);if(symbol==null||symbol.ttype==RIGHTBRACKET)
-return[null,str,null];}
-str=AMremoveCharsAndBlanks(str,symbol.input.length);switch(symbol.ttype){case SPACE:node=AMcreateElementMathML(symbol.tag);node.setAttribute(symbol.atname,symbol.atval);return[node,str,symbol.tag];case UNDEROVER:if(isIE){if(symbol.input.substr(0,4)=="\\big"){str="\\"+symbol.input.substr(4)+str;symbol=AMgetSymbol(str);symbol.ttype=UNDEROVER;str=AMremoveCharsAndBlanks(str,symbol.input.length);}}
-return[AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)),str,symbol.tag];case CONST:var output=symbol.output;if(isIE){if(symbol.input=="'")
-output="\u2032";else if(symbol.input=="''")
-output="\u2033";else if(symbol.input=="'''")
-output="\u2033\u2032";else if(symbol.input=="''''")
-output="\u2033\u2033";else if(symbol.input=="\\square")
-output="\u25A1";else if(symbol.input.substr(0,5)=="\\frac"){var denom=symbol.input.substr(6,1);if(denom=="5"||denom=="6"){str=symbol.input.replace(/\\frac/,"\\frac ")+str;return[node,str,symbol.tag];}}}
-node=AMcreateMmlNode(symbol.tag,document.createTextNode(output));return[node,str,symbol.tag];case LONG:node=AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output));node.setAttribute("minsize","1.5");node.setAttribute("maxsize","1.5");node=AMcreateMmlNode("mover",node);node.appendChild(AMcreateElementMathML("mspace"));return[node,str,symbol.tag];case STRETCHY:if(isIE&&symbol.input=="\\backslash")
-symbol.output="\\";node=AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output));if(symbol.input=="|"||symbol.input=="\\vert"||symbol.input=="\\|"||symbol.input=="\\Vert"){node.setAttribute("lspace","0em");node.setAttribute("rspace","0em");}
-node.setAttribute("maxsize",symbol.atval);if(symbol.rtag!=null)
-return[node,str,symbol.rtag];else
-return[node,str,symbol.tag];case BIG:var atval=symbol.atval;if(isIE)
-atval=symbol.ieval;symbol=AMgetSymbol(str);if(symbol==null)
-return[null,str,null];str=AMremoveCharsAndBlanks(str,symbol.input.length);node=AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output));if(isIE){var space=AMcreateElementMathML("mspace");space.setAttribute("height",atval+"ex");node=AMcreateMmlNode("mrow",node);node.appendChild(space);}else{node.setAttribute("minsize",atval);node.setAttribute("maxsize",atval);}
-return[node,str,symbol.tag];case LEFTBRACKET:if(symbol.input=="\\left"){symbol=AMgetSymbol(str);if(symbol!=null){if(symbol.input==".")
-symbol.invisible=true;str=AMremoveCharsAndBlanks(str,symbol.input.length);}}
-result=AMparseExpr(str,true,false);if(symbol==null||(typeof symbol.invisible=="boolean"&&symbol.invisible))
-node=AMcreateMmlNode("mrow",result[0]);else{node=AMcreateMmlNode("mo",document.createTextNode(symbol.output));node=AMcreateMmlNode("mrow",node);node.appendChild(result[0]);}
-return[node,result[1],result[2]];case MATRIX:if(symbol.input=="\\begin{array}"){var mask="";symbol=AMgetSymbol(str);str=AMremoveCharsAndBlanks(str,0);if(symbol==null)
-mask="l";else{str=AMremoveCharsAndBlanks(str,symbol.input.length);if(symbol.input!="{")
-mask="l";else do{symbol=AMgetSymbol(str);if(symbol!=null){str=AMremoveCharsAndBlanks(str,symbol.input.length);if(symbol.input!="}")
-mask=mask+symbol.input;}}while(symbol!=null&&symbol.input!=""&&symbol.input!="}");}
-result=AMparseExpr("{"+str,true,true);node=AMcreateMmlNode("mtable",result[0]);mask=mask.replace(/l/g,"left ");mask=mask.replace(/r/g,"right ");mask=mask.replace(/c/g,"center ");node.setAttribute("columnalign",mask);node.setAttribute("displaystyle","false");if(isIE)
-return[node,result[1],null];var lspace=AMcreateElementMathML("mspace");lspace.setAttribute("width","0.167em");var rspace=AMcreateElementMathML("mspace");rspace.setAttribute("width","0.167em");var node1=AMcreateMmlNode("mrow",lspace);node1.appendChild(node);node1.appendChild(rspace);return[node1,result[1],null];}else{result=AMparseExpr("{"+str,true,true);node=AMcreateMmlNode("mtable",result[0]);if(isIE)
-node.setAttribute("columnspacing","0.25em");else
-node.setAttribute("columnspacing","0.167em");node.setAttribute("columnalign","right center left");node.setAttribute("displaystyle","true");node=AMcreateMmlNode("mrow",node);return[node,result[1],null];}
-case TEXT:if(str.charAt(0)=="{")i=str.indexOf("}");else i=0;if(i==-1)
-i=str.length;st=str.slice(1,i);if(st.charAt(0)==" "){node=AMcreateElementMathML("mspace");node.setAttribute("width","0.33em");newFrag.appendChild(node);}
-newFrag.appendChild(AMcreateMmlNode(symbol.tag,document.createTextNode(st)));if(st.charAt(st.length-1)==" "){node=AMcreateElementMathML("mspace");node.setAttribute("width","0.33em");newFrag.appendChild(node);}
-str=AMremoveCharsAndBlanks(str,i+1);return[AMcreateMmlNode("mrow",newFrag),str,null];case UNARY:result=AMparseSexpr(str);if(result[0]==null)return[AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)),str];if(typeof symbol.func=="boolean"&&symbol.func){st=str.charAt(0);if(st=="^"||st=="_"||st==","){return[AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)),str,symbol.tag];}else{node=AMcreateMmlNode("mrow",AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)));if(isIE){var space=AMcreateElementMathML("mspace");space.setAttribute("width","0.167em");node.appendChild(space);}
-node.appendChild(result[0]);return[node,result[1],symbol.tag];}}
-if(symbol.input=="\\sqrt"){if(isIE){var space=AMcreateElementMathML("mspace");space.setAttribute("height","1.2ex");space.setAttribute("width","0em");node=AMcreateMmlNode(symbol.tag,result[0])
-node.appendChild(space);return[node,result[1],symbol.tag];}else
-return[AMcreateMmlNode(symbol.tag,result[0]),result[1],symbol.tag];}else if(typeof symbol.acc=="boolean"&&symbol.acc){node=AMcreateMmlNode(symbol.tag,result[0]);var output=symbol.output;if(isIE){if(symbol.input=="\\hat")
-output="\u0302";else if(symbol.input=="\\widehat")
-output="\u005E";else if(symbol.input=="\\bar")
-output="\u00AF";else if(symbol.input=="\\grave")
-output="\u0300";else if(symbol.input=="\\tilde")
-output="\u0303";}
-var node1=AMcreateMmlNode("mo",document.createTextNode(output));if(symbol.input=="\\vec"||symbol.input=="\\check")
-node1.setAttribute("maxsize","1.2");if(isIE&&symbol.input=="\\bar")
-node1.setAttribute("maxsize","0.5");if(symbol.input=="\\underbrace"||symbol.input=="\\underline")
-node1.setAttribute("accentunder","true");else
-node1.setAttribute("accent","true");node.appendChild(node1);if(symbol.input=="\\overbrace"||symbol.input=="\\underbrace")
-node.ttype=UNDEROVER;return[node,result[1],symbol.tag];}else{if(!isIE&&typeof symbol.codes!="undefined"){for(i=0;i<result[0].childNodes.length;i++)
-if(result[0].childNodes[i].nodeName=="mi"||result[0].nodeName=="mi"){st=(result[0].nodeName=="mi"?result[0].firstChild.nodeValue:result[0].childNodes[i].firstChild.nodeValue);var newst=[];for(var j=0;j<st.length;j++)
-if(st.charCodeAt(j)>64&&st.charCodeAt(j)<91)newst=newst+
-String.fromCharCode(symbol.codes[st.charCodeAt(j)-65]);else newst=newst+st.charAt(j);if(result[0].nodeName=="mi")
-result[0]=AMcreateElementMathML("mo").appendChild(document.createTextNode(newst));else result[0].replaceChild(AMcreateElementMathML("mo").appendChild(document.createTextNode(newst)),result[0].childNodes[i]);}}
-node=AMcreateMmlNode(symbol.tag,result[0]);node.setAttribute(symbol.atname,symbol.atval);if(symbol.input=="\\scriptstyle"||symbol.input=="\\scriptscriptstyle")
-node.setAttribute("displaystyle","false");return[node,result[1],symbol.tag];}
-case BINARY:result=AMparseSexpr(str);if(result[0]==null)return[AMcreateMmlNode("mo",document.createTextNode(symbol.input)),str,null];result2=AMparseSexpr(result[1]);if(result2[0]==null)return[AMcreateMmlNode("mo",document.createTextNode(symbol.input)),str,null];if(symbol.input=="\\textcolor"||symbol.input=="\\colorbox"){var tclr=str.match(/\{\s*([#\w]+)\s*\}/);str=str.replace(/\{\s*[#\w]+\s*\}/,"");if(tclr!=null){if(IsColorName.test(tclr[1].toLowerCase())){tclr=LaTeXColor[tclr[1].toLowerCase()];}else{tclr=tclr[1];}
-node=AMcreateElementMathML("mstyle");node.setAttribute(symbol.atval,tclr);node.appendChild(result2[0]);return[node,result2[1],symbol.tag];}}
-if(symbol.input=="\\root"||symbol.input=="\\stackrel")newFrag.appendChild(result2[0]);newFrag.appendChild(result[0]);if(symbol.input=="\\frac")newFrag.appendChild(result2[0]);return[AMcreateMmlNode(symbol.tag,newFrag),result2[1],symbol.tag];case INFIX:str=AMremoveCharsAndBlanks(str,symbol.input.length);return[AMcreateMmlNode("mo",document.createTextNode(symbol.output)),str,symbol.tag];default:return[AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)),str,symbol.tag];}}
-function AMparseIexpr(str){var symbol,sym1,sym2,node,result,tag,underover;str=AMremoveCharsAndBlanks(str,0);sym1=AMgetSymbol(str);result=AMparseSexpr(str);node=result[0];str=result[1];tag=result[2];symbol=AMgetSymbol(str);if(symbol.ttype==INFIX){str=AMremoveCharsAndBlanks(str,symbol.input.length);result=AMparseSexpr(str);if(result[0]==null)
-result[0]=AMcreateMmlNode("mo",document.createTextNode("\u25A1"));str=result[1];tag=result[2];if(symbol.input=="_"||symbol.input=="^"){sym2=AMgetSymbol(str);tag=null;underover=((sym1.ttype==UNDEROVER)||(node.ttype==UNDEROVER));if(symbol.input=="_"&&sym2.input=="^"){str=AMremoveCharsAndBlanks(str,sym2.input.length);var res2=AMparseSexpr(str);str=res2[1];tag=res2[2];node=AMcreateMmlNode((underover?"munderover":"msubsup"),node);node.appendChild(result[0]);node.appendChild(res2[0]);}else if(symbol.input=="_"){node=AMcreateMmlNode((underover?"munder":"msub"),node);node.appendChild(result[0]);}else{node=AMcreateMmlNode((underover?"mover":"msup"),node);node.appendChild(result[0]);}
-node=AMcreateMmlNode("mrow",node);}else{node=AMcreateMmlNode(symbol.tag,node);if(symbol.input=="\\atop"||symbol.input=="\\choose")
-node.setAttribute("linethickness","0ex");node.appendChild(result[0]);if(symbol.input=="\\choose")
-node=AMcreateMmlNode("mfenced",node);}}
-return[node,str,tag];}
-function AMparseExpr(str,rightbracket,matrix){var symbol,node,result,i,tag,newFrag=document.createDocumentFragment();do{str=AMremoveCharsAndBlanks(str,0);result=AMparseIexpr(str);node=result[0];str=result[1];tag=result[2];symbol=AMgetSymbol(str);if(node!=undefined){if((tag=="mn"||tag=="mi")&&symbol!=null&&typeof symbol.func=="boolean"&&symbol.func){var space=AMcreateElementMathML("mspace");space.setAttribute("width","0.167em");node=AMcreateMmlNode("mrow",node);node.appendChild(space);}
-newFrag.appendChild(node);}}while((symbol.ttype!=RIGHTBRACKET)&&symbol!=null&&symbol.output!="");tag=null;if(symbol.ttype==RIGHTBRACKET){if(symbol.input=="\\right"){str=AMremoveCharsAndBlanks(str,symbol.input.length);symbol=AMgetSymbol(str);if(symbol!=null&&symbol.input==".")
-symbol.invisible=true;if(symbol!=null)
-tag=symbol.rtag;}
-if(symbol!=null)
-str=AMremoveCharsAndBlanks(str,symbol.input.length);var len=newFrag.childNodes.length;if(matrix&&len>0&&newFrag.childNodes[len-1].nodeName=="mrow"&&len>1&&newFrag.childNodes[len-2].nodeName=="mo"&&newFrag.childNodes[len-2].firstChild.nodeValue=="&"){var pos=[];var m=newFrag.childNodes.length;for(i=0;matrix&&i<m;i=i+2){pos[i]=[];node=newFrag.childNodes[i];for(var j=0;j<node.childNodes.length;j++)
-if(node.childNodes[j].firstChild.nodeValue=="&")
-pos[i][pos[i].length]=j;}
-var row,frag,n,k,table=document.createDocumentFragment();for(i=0;i<m;i=i+2){row=document.createDocumentFragment();frag=document.createDocumentFragment();node=newFrag.firstChild;n=node.childNodes.length;k=0;for(j=0;j<n;j++){if(typeof pos[i][k]!="undefined"&&j==pos[i][k]){node.removeChild(node.firstChild);row.appendChild(AMcreateMmlNode("mtd",frag));k++;}else frag.appendChild(node.firstChild);}
-row.appendChild(AMcreateMmlNode("mtd",frag));if(newFrag.childNodes.length>2){newFrag.removeChild(newFrag.firstChild);newFrag.removeChild(newFrag.firstChild);}
-table.appendChild(AMcreateMmlNode("mtr",row));}
-return[table,str];}
-if(typeof symbol.invisible!="boolean"||!symbol.invisible){node=AMcreateMmlNode("mo",document.createTextNode(symbol.output));newFrag.appendChild(node);}}
-return[newFrag,str,tag];}
-function AMparseMath(str){var result,node=AMcreateElementMathML("mstyle");var cclr=str.match(/\\color\s*\{\s*([#\w]+)\s*\}/);str=str.replace(/\\color\s*\{\s*[#\w]+\s*\}/g,"");if(cclr!=null){if(IsColorName.test(cclr[1].toLowerCase())){cclr=LaTeXColor[cclr[1].toLowerCase()];}else{cclr=cclr[1];}
-node.setAttribute("mathcolor",cclr);}else{if(mathcolor!="")node.setAttribute("mathcolor",mathcolor);};if(mathfontfamily!="")node.setAttribute("fontfamily",mathfontfamily);node.appendChild(AMparseExpr(str.replace(/^\s+/g,""),false,false)[0]);node=AMcreateMmlNode("math",node);if(showasciiformulaonhover)
-node.setAttribute("title",str.replace(/\s+/g," "));if(false){var fnode=AMcreateElementXHTML("font");fnode.setAttribute("face",mathfontfamily);fnode.appendChild(node);return fnode;}
-return node;}
-function AMstrarr2docFrag(arr,linebreaks){var newFrag=document.createDocumentFragment();var expr=false;for(var i=0;i<arr.length;i++){if(expr)newFrag.appendChild(AMparseMath(arr[i]));else{var arri=(linebreaks?arr[i].split("\n\n"):[arr[i]]);newFrag.appendChild(AMcreateElementXHTML("span").appendChild(document.createTextNode(arri[0])));for(var j=1;j<arri.length;j++){newFrag.appendChild(AMcreateElementXHTML("p"));newFrag.appendChild(AMcreateElementXHTML("span").appendChild(document.createTextNode(arri[j])));}}
-expr=!expr;}
-return newFrag;}
-function AMprocessNodeR(n,linebreaks){var mtch,str,arr,frg,i;if(n.childNodes.length==0){if((n.nodeType!=8||linebreaks)&&n.parentNode.nodeName!="form"&&n.parentNode.nodeName!="FORM"&&n.parentNode.nodeName!="textarea"&&n.parentNode.nodeName!="TEXTAREA"&&n.parentNode.nodeName!="pre"&&n.parentNode.nodeName!="PRE"){str=n.nodeValue;if(!(str==null)){str=str.replace(/\r\n\r\n/g,"\n\n");str=str.replace(/\x20+/g," ");str=str.replace(/\s*\r\n/g," ");mtch=(str.indexOf("\$")==-1?false:true);str=str.replace(/([^\\])\$/g,"$1 \$");str=str.replace(/^\$/," \$");arr=str.split(" \$");for(i=0;i<arr.length;i++)
-arr[i]=arr[i].replace(/\\\$/g,"\$");if(arr.length>1||mtch){if(checkForMathML){checkForMathML=false;var nd=AMisMathMLavailable();AMnoMathML=nd!=null;if(AMnoMathML&&notifyIfNoMathML)
-if(alertIfNoMathML)
-alert("To view the ASCIIMathML notation use Internet Explorer 6 +\nMathPlayer (free from www.dessci.com)\nor Firefox/Mozilla/Netscape");else AMbody.insertBefore(nd,AMbody.childNodes[0]);}
-if(!AMnoMathML){frg=AMstrarr2docFrag(arr,n.nodeType==8);var len=frg.childNodes.length;n.parentNode.replaceChild(frg,n);return len-1;}else return 0;}}}else return 0;}else if(n.nodeName!="math"){for(i=0;i<n.childNodes.length;i++)
-i+=AMprocessNodeR(n.childNodes[i],linebreaks);}
-return 0;}
-function AMprocessNode(n,linebreaks,spanclassAM){var frag,st;if(spanclassAM!=null){frag=document.getElementsByTagName("span")
-for(var i=0;i<frag.length;i++)
-if(frag[i].className=="AM")
-AMprocessNodeR(frag[i],linebreaks);}else{try{st=n.innerHTML;}catch(err){}
-if(st==null||st.indexOf("\$")!=-1)
-AMprocessNodeR(n,linebreaks);}
-if(isIE){frag=document.getElementsByTagName('math');for(var i=0;i<frag.length;i++)frag[i].update()}}
-var inAppendix=false;var sectionCntr=0;var IEcommentWarning=true;var biblist=[];var bibcntr=0;var LaTeXCounter=[];LaTeXCounter["definition"]=0;LaTeXCounter["proposition"]=0;LaTeXCounter["lemma"]=0;LaTeXCounter["theorem"]=0;LaTeXCounter["corollary"]=0;LaTeXCounter["example"]=0;LaTeXCounter["exercise"]=0;LaTeXCounter["subsection"]=0;LaTeXCounter["subsubsection"]=0;LaTeXCounter["figure"]=0;LaTeXCounter["equation"]=0;LaTeXCounter["table"]=0;var LaTeXColor=[];LaTeXColor["greenyellow"]="#D9FF4F";LaTeXColor["yellow"]="#FFFF00";LaTeXColor["goldenrod"]="#FFE529";LaTeXColor["dandelion"]="#FFB529";LaTeXColor["apricot"]="#FFAD7A";LaTeXColor["peach"]="#FF804D";LaTeXColor["melon"]="#FF8A80";LaTeXColor["yelloworange"]="#FF9400";LaTeXColor["orange"]="#FF6321";LaTeXColor["burntorange"]="#FF7D00";LaTeXColor["bittersweet"]="#C20300";LaTeXColor["redorange"]="#FF3B21";LaTeXColor["mahogany"]="#A60000";LaTeXColor["maroon"]="#AD0000";LaTeXColor["brickred"]="#B80000";LaTeXColor["red"]="#FF0000";LaTeXColor["orangered"]="#FF0080";LaTeXColor["rubinered"]="#FF00DE";LaTeXColor["wildstrawberry"]="#FF0A9C";LaTeXColor["salmon"]="#FF789E";LaTeXColor["carnationpink"]="#FF5EFF";LaTeXColor["magenta"]="#FF00FF";LaTeXColor["violetred"]="#FF30FF";LaTeXColor["rhodamine"]="#FF2EFF";LaTeXColor["mulberry"]="#A314FA";LaTeXColor["redviolet"]="#9600A8";LaTeXColor["fuchsia"]="#7303EB";LaTeXColor["lavender"]="#FF85FF";LaTeXColor["thistle"]="#E069FF";LaTeXColor["orchid"]="#AD5CFF";LaTeXColor["darkorchid"]="#9933CC";LaTeXColor["purple"]="#8C24FF";LaTeXColor["plum"]="#8000FF";LaTeXColor["violet"]="#361FFF";LaTeXColor["royalpurple"]="#401AFF";LaTeXColor["blueviolet"]="#1A0DF5";LaTeXColor["periwinkle"]="#6E73FF";LaTeXColor["cadetblue"]="#616EC4";LaTeXColor["cornflowerblue"]="#59DEFF";LaTeXColor["midnightblue"]="#007091";LaTeXColor["navyblue"]="#0F75FF";LaTeXColor["royalblue"]="#0080FF";LaTeXColor["blue"]="#0000FF";LaTeXColor["cerulean"]="#0FE3FF";LaTeXColor["cyan"]="#00FFFF";LaTeXColor["processblue"]="#0AFFFF";LaTeXColor["skyblue"]="#61FFE0";LaTeXColor["turquoise"]="#26FFCC";LaTeXColor["tealblue"]="#1FFAA3";LaTeXColor["aquamarine"]="#2EFFB2";LaTeXColor["bluegreen"]="#26FFAB";LaTeXColor["emerald"]="#00FF80";LaTeXColor["junglegreen"]="#03FF7A";LaTeXColor["seagreen"]="#4FFF80";LaTeXColor["green"]="#00FF00";LaTeXColor["forestgreen"]="#00E000";LaTeXColor["pinegreen"]="#00BF29";LaTeXColor["limegreen"]="#80FF00";LaTeXColor["yellowgreen"]="#8FFF42";LaTeXColor["springgreen"]="#BDFF3D";LaTeXColor["olivegreen"]="#009900";LaTeXColor["rawsienna"]="#8C0000";LaTeXColor["sepia"]="#4D0000";LaTeXColor["brown"]="#660000";LaTeXColor["tan"]="#DB9470";LaTeXColor["gray"]="#808080";LaTeXColor["grey"]="#808080";LaTeXColor["black"]="#000000";LaTeXColor["white"]="#FFFFFF";var IsColorName=/^(?:greenyellow|yellow|goldenrod|dandelion|apricot|peach|melon|yelloworange|orange|burntorange|bittersweet|redorange|mahogany|maroon|brickred|red|orangered|rubinered|wildstrawberry|salmon|carnationpink|magenta|violetred|rhodamine|mulberry|redviolet|fuchsia|lavender|thistle|orchid|darkorchid|purple|plum|violet|royalpurple|blueviolet|periwinkle|cadetblue|cornflowerblue|midnightblue|navyblue|royalblue|blue|cerulean|cyan|processblue|skyblue|turquoise|tealblue|aquamarine|bluegreen|emerald|junglegreen|seagreen|green|forestgreen|pinegreen|limegreen|yellowgreen|springgreen|olivegreen|rawsienna|sepia|brown|tan|gray|grey|black|white)$/;var IsCounter=/^(?:definition|proposition|lemma|theorem|corollary|example|exercise|subsection|subsubsection|figure|equation|table)$/;var IsLaTeXElement=/^(?:displayequation|title|author|address|date|abstract|keyword|section|subsection|subsubsection|ref|cite|thebibliography|definition|proposition|lemma|theorem|corollary|example|exercise|itemize|enumerate|enddefinition|endproposition|endlemma|endtheorem|endcorollary|endexample|endexercise|enditemize|endenumerate|LaTeXMathMLlabel|LaTeXMathML|smallskip|medskip|bigskip|quote|quotation|endquote|endquotation|center|endcenter|description|enddescription|inlinemath)$/;var IsTextOnlyArea=/^(?:form|textarea|pre)$/i;var tableid=0;function makeNumberString(cntr){if(sectionCntr>0){if(inAppendix){return"A"+sectionCntr+"."+cntr;}else{return sectionCntr+"."+cntr;}}else{return""+cntr;}};function LaTeXpreProcess(thebody){var TheBody=thebody;if(TheBody.hasChildNodes()){if(!(IsLaTeXElement.test(TheBody.className)))
-{for(var i=0;i<TheBody.childNodes.length;i++){LaTeXpreProcess(TheBody.childNodes[i])}}}
-else{if(TheBody.nodeType==3&&!(IsTextOnlyArea.test(TheBody.parentNode.nodeName)))
-{var str=TheBody.nodeValue;if(!(str==null)){str=str.replace(/\\%/g,"<per>");str=str.replace(/%[^\n]*(?=\n)/g,"");str=str.replace(/%[^\r]*(?=\r)/g,"");str=str.replace(/%[^\n]*$/,"")
-if(isIE&&str.match(/%/g)!=null&&IEcommentWarning){alert("Comments may not have parsed properly.  Try putting in <pre class='LaTeX><div>..</div></pre> structure.");IEcommentWarning=false;}
-str=str.replace(/<per>/g,"%");if(str.match(/XXX[\s\S]*/)!=null){var tmp=str.match(/XXX[\s\S]*/)[0];var tmpstr=tmp.charCodeAt(7)+"::"+tmp.charCodeAt(8)+"::"+tmp.charCodeAt(9)+"::"+tmp.charCodeAt(10)+"::"+tmp.charCodeAt(11)+"::"+tmp.charCodeAt(12)+"::"+tmp.charCodeAt(13);alert(tmpstr);}
-str=str.replace(/([^\\])\\(\s)/g,"$1\u00A0$2");str=str.replace(/\\quad/g,"\u2001");str=str.replace(/\\qquad/g,"\u2001\u2001");str=str.replace(/\\enspace/g,"\u2002");str=str.replace(/\\;/g,"\u2004");str=str.replace(/\\:/g,"\u2005");str=str.replace(/\\,/g,"\u2006");str=str.replace(/\\thinspace/g,"\u200A");str=str.replace(/([^\\])~/g,"$1\u00A0");str=str.replace(/\\~/g,"~");str=str.replace(/\\\[/g," <DEQ> $\\displaystyle{");str=str.replace(/\\\]/g,"}$ <DEQ> ");str=str.replace(/\$\$/g,"${$<DEQ>$}$");str=str.replace(/\\begin\s*\{\s*array\s*\}/g,"\\begin{array}");str=str.replace(/\\end\s*\{\s*array\s*\}/g,"\\end{array}");str=str.replace(/\\begin\s*\{\s*eqnarray\s*\}/g,"  <DEQ>eqno$\\begin{eqnarray}");str=str.replace(/\\end\s*\{\s*eqnarray\s*\}/g,"\\end{eqnarray}$<DEQ>  ");str=str.replace(/\\begin\s*\{\s*eqnarray\*\s*\}/g,"  <DEQ>$\\begin{eqnarray}");str=str.replace(/\\end\s*\{\s*eqnarray\*\s*\}/g,"\\end{eqnarray}$<DEQ>  ");str=str.replace(/\\begin\s*\{\s*displaymath\s*\}/g," <DEQ> $\\displaystyle{");str=str.replace(/\\end\s*\{\s*displaymath\s*\}/g,"}$ <DEQ> ");str=str.replace(/\\begin\s*\{\s*equation\s*\*\s*\}/g," <DEQ> $\\displaystyle{");str=str.replace(/\\end\s*\{\s*equation\s*\*\s*\}/g,"}$ <DEQ> ");str=str.replace(/\\begin\s*\{\s*equation\s*\}/g," <DEQ>eqno$\\displaystyle{");str=str.replace(/\\end\s*\{\s*equation\s*\}/g,"}$ <DEQ> ");str=str.split("<DEQ>");var newFrag=document.createDocumentFragment();for(var i=0;i<str.length;i++){if(i%2){var DEQtable=document.createElement("table");DEQtable.className='displayequation';var DEQtbody=document.createElement("tbody");var DEQtr=document.createElement("tr");var DEQtdeq=document.createElement("td");DEQtdeq.className='eq';str[i]=str[i].replace(/\$\}\$/g,"$\\displaystyle{");str[i]=str[i].replace(/\$\{\$/g,"}");var lbl=str[i].match(/\\label\s*\{\s*(\w+)\s*\}/);var ISeqno=str[i].match(/^eqno/);str[i]=str[i].replace(/^eqno/," ");str[i]=str[i].replace(/\\label\s*\{\s*\w+\s*\}/," ");DEQtdeq.appendChild(document.createTextNode(str[i]));DEQtr.appendChild(DEQtdeq);str[i]=str[i].replace(/\\nonumber/g,"");if(ISeqno!=null||lbl!=null){var DEQtdno=document.createElement("td");DEQtdno.className='eqno';LaTeXCounter["equation"]++;var eqnoString=makeNumberString(LaTeXCounter["equation"]);var DEQanchor=document.createElement("a");if(lbl!=null){DEQanchor.id=lbl[1]};DEQanchor.className="eqno";var anchorSpan=document.createElement("span");anchorSpan.className="eqno";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(eqnoString));DEQanchor.appendChild(anchorSpan);DEQtdno.appendChild(DEQanchor);var DEQspan=document.createElement("span");DEQspan.className="eqno";DEQspan.appendChild(document.createTextNode("("+eqnoString+")"));DEQtdno.appendChild(DEQspan);DEQtr.appendChild(DEQtdno);}
-DEQtbody.appendChild(DEQtr);DEQtable.appendChild(DEQtbody);newFrag.appendChild(DEQtable);}
-else{str[i]=str[i].replace(/\$\}\$/g,"");str[i]=str[i].replace(/\$\{\$/g,"");str[i]=str[i].replace(/\\maketitle/g,"");str[i]=str[i].replace(/\\begin\s*\{\s*document\s*\}/g,"");str[i]=str[i].replace(/\\end\s*\{\s*document\s*\}/g,"");str[i]=str[i].replace(/\\documentclass[^\}]*?\}/g,"");str[i]=str[i].replace(/\\usepackage[^\}]*?\}/g,"");str[i]=str[i].replace(/\\noindent/g,"");str[i]=str[i].replace(/\\notag/g,"");str[i]=str[i].replace(/\\ref\s*\{\s*(\w+)\}/g," \\[ref\\]$1\\[ ");str[i]=str[i].replace(/\\url\s*\{\s*([^\}\n]+)\}/g," \\[url\\]$1\\[ ");str[i]=str[i].replace(/\\href\s*\{\s*([^\}]+)\}\s*\{\s*([^\}]+)\}/g," \\[href\\]$1\\]$2\\[ ");str[i]=str[i].replace(/\\cite\s*\{\s*(\w+)\}/g," \\[cite\\]$1\\[ ");str[i]=str[i].replace(/\\qed/g,"\u220E");str[i]=str[i].replace(/\\endproof/g,"\u220E");str[i]=str[i].replace(/\\proof/g,"\\textbf{Proof: }");str[i]=str[i].replace(/\\n(?=\s)/g," \\[br\\] \\[ ");str[i]=str[i].replace(/\\newline/g," \\[br\\] \\[ ");str[i]=str[i].replace(/\\linebreak/g," \\[br\\] \\[ ");str[i]=str[i].replace(/\\smallskip/g," \\[logicalbreak\\]smallskip\\[ ");str[i]=str[i].replace(/\\medskip/g," \\[logicalbreak\\]medskip\\[ ");str[i]=str[i].replace(/\\bigskip/g," \\[logicalbreak\\]bigskip\\[ ");str[i]=str[i].replace(/[\n\r]+[ \f\n\r\t\v\u2028\u2029]*[\n\r]+/g," \\[logicalbreak\\]LaTeXMathML\\[ ");if(isIE){str[i]=str[i].replace(/\r/g," ");}
-str[i]=str[i].replace(/\\bibitem\s*([^\{]*\{\s*\w*\s*\})/g," \\[bibitem\\]$1\\[ ");str[i]=str[i].replace(/\\bibitem\s*/g," \\[bibitem\\] \\[ ");str[i]=str[i].replace(/\\item\s*\[\s*(\w+)\s*\]/g," \\[alistitem\\]$1\\[ ");str[i]=str[i].replace(/\\item\s*/g," \\[alistitem\\] \\[ ");str[i]=str[i].replace(/\\appendix/g," \\[appendix\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*figure\s*\}([\s\S]+?)\\end\s*\{\s*figure\s*\}/g," \\[figure\\]$1\\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*table\s*\}([\s\S]+?)\\end\s*\{\s*table\s*\}/g," \\[table\\]$1\\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*theorem\s*\}/g," \\[theorem\\]Theorem \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*theorem\s*\}/g," \\[endtheorem\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*definition\s*\}/g," \\[definition\\]Definition \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*definition\s*\}/g," \\[enddefinition\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*lemma\s*\}/g," \\[lemma\\]Lemma \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*lemma\s*\}/g," \\[endlemma\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*corollary\s*\}/g," \\[corollary\\]Corollary \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*corollary\s*\}/g," \\[endcorollary\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*proposition\s*\}/g," \\[proposition\\]Proposition \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*proposition\s*\}/g," \\[endproposition\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*example\s*\}/g," \\[example\\]Example \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*example\s*\}/g," \\[endexample\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*exercise\s*\}/g," \\[exercise\\]Exercise \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*exercise\s*\}/g," \\[endexercise\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*thebibliography\s*\}\s*\{\s*\w+\s*\}/g," \\[thebibliography\\]References \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*thebibliography\s*\}/g," \\[thebibliography\\]References \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*thebibliography\s*\}/g," \\[endthebibliography\\]References \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*proof\s*\}/g," \\[proof\\]Proof: \\[ ");if(isIE){str[i]=str[i].replace(/\\end\s*\{\s*proof\s*\}/g,"\u220E \\[endproof\\] \\[ ");}else{str[i]=str[i].replace(/\\end\s*\{\s*proof\s*\}/g," \\[endproof\\] \\[ ");}
-str[i]=str[i].replace(/\\title\s*\{\s*([^\}]+)\}/g," \\[title\\] \\[$1 \\[endtitle\\] \\[ ");str[i]=str[i].replace(/\\author\s*\{\s*([^\}]+)\}/g," \\[author\\] \\[$1 \\[endauthor\\] \\[ ");str[i]=str[i].replace(/\\address\s*\{\s*([^\}]+)\}/g," \\[address\\] \\[$1 \\[endaddress\\] \\[ ");str[i]=str[i].replace(/\\date\s*\{\s*([^\}]+)\}/g," \\[date\\] \\[$1 \\[enddate\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*keyword\s*\}/g," \\[keyword\\] \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*keyword\s*\}/g," \\[endkeyword\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*abstract\s*\}/g," \\[abstract\\] \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*abstract\s*\}/g," \\[endabstract\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*(?!array|tabular)(\w+)\s*\}/g," \\[$1\\] \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*(?!array|tabular)(\w+)\s*\}/g," \\[end$1\\] \\[ ");var sectionIndex=str[i].search(/\\section\s*\{\s*[\s\S]+\}/);while(sectionIndex>=0){str[i]=str[i].replace(/\\section\s*\{/," \\[section\\]");var delimcnt=1;for(var ii=sectionIndex;ii<str[i].length;ii++){if(str[i].charAt(ii)=="{"){delimcnt++};if(str[i].charAt(ii)=="}"){delimcnt--};if(delimcnt==0){str[i]=str[i].substring(0,ii)+"\\[ "+str[i].substring(ii+1,str[i].length);break;}};sectionIndex=str[i].search(/\\section\s*\{\s*[\s\S]+\}/);}
-sectionIndex=str[i].search(/\\subsection\s*\{\s*[\s\S]+\}/);while(sectionIndex>=0){str[i]=str[i].replace(/\\subsection\s*\{/," \\[subsection\\]");var delimcnt=1;for(var ii=sectionIndex;ii<str[i].length;ii++){if(str[i].charAt(ii)=="{"){delimcnt++};if(str[i].charAt(ii)=="}"){delimcnt--};if(delimcnt==0){str[i]=str[i].substring(0,ii)+"\\[ "+str[i].substring(ii+1,str[i].length);break;}};sectionIndex=str[i].search(/\\subsection\s*\{\s*[\s\S]+\}/);}
-sectionIndex=str[i].search(/\\subsubsection\s*\{\s*[\s\S]+\}/);while(sectionIndex>=0){str[i]=str[i].replace(/\\subsubsection\s*\{/," \\[subsubsection\\]");var delimcnt=1;for(var ii=sectionIndex;ii<str[i].length;ii++){if(str[i].charAt(ii)=="{"){delimcnt++};if(str[i].charAt(ii)=="}"){delimcnt--};if(delimcnt==0){str[i]=str[i].substring(0,ii)+"\\[ "+str[i].substring(ii+1,str[i].length);break;}};sectionIndex=str[i].search(/\\subsubsection\s*\{\s*[\s\S]+\}/);}
-var CatToNextEven="";var strtmp=str[i].split("\\[");for(var j=0;j<strtmp.length;j++){if(j%2){var strtmparray=strtmp[j].split("\\]");switch(strtmparray[0]){case"section":var nodeTmp=document.createElement("H2");nodeTmp.className='section';sectionCntr++;for(var div in LaTeXCounter){LaTeXCounter[div]=0};var nodeAnchor=document.createElement("a");if(inAppendix){nodeAnchor.className='appendixsection';}else{nodeAnchor.className='section';}
-var nodeNumString=makeNumberString("");var anchorSpan=document.createElement("span");anchorSpan.className="section";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(nodeNumString));nodeAnchor.appendChild(anchorSpan);nodeTmp.appendChild(nodeAnchor);var nodeSpan=document.createElement("span");nodeSpan.className='section';nodeSpan.appendChild(document.createTextNode(nodeNumString+" "));nodeTmp.appendChild(nodeSpan);nodeTmp.appendChild(document.createTextNode(strtmparray[1]));newFrag.appendChild(nodeTmp);break;case"subsection":var nodeTmp=document.createElement("H3");nodeTmp.className='subsection';LaTeXCounter["subsection"]++;LaTeXCounter["subsubsection"]=0;var nodeAnchor=document.createElement("a");nodeAnchor.className='subsection';var nodeNumString=makeNumberString(LaTeXCounter["subsection"]);var anchorSpan=document.createElement("span");anchorSpan.className="subsection";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(nodeNumString));nodeAnchor.appendChild(anchorSpan);nodeTmp.appendChild(nodeAnchor);var nodeSpan=document.createElement("span");nodeSpan.className='subsection';nodeSpan.appendChild(document.createTextNode(nodeNumString+". "));nodeTmp.appendChild(nodeSpan);nodeTmp.appendChild(document.createTextNode(strtmparray[1]));newFrag.appendChild(nodeTmp);break;case"subsubsection":var nodeTmp=document.createElement("H4");nodeTmp.className='subsubsection';LaTeXCounter["subsubsection"]++;var nodeAnchor=document.createElement("a");nodeAnchor.className='subsubsection';var nodeNumString=makeNumberString(LaTeXCounter["subsection"]+"."+LaTeXCounter["subsubsection"]);var anchorSpan=document.createElement("span");anchorSpan.className="subsubsection";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(nodeNumString));nodeAnchor.appendChild(anchorSpan);nodeTmp.appendChild(nodeAnchor);var nodeSpan=document.createElement("span");nodeSpan.className='subsubsection';nodeSpan.appendChild(document.createTextNode(nodeNumString+". "));nodeTmp.appendChild(nodeSpan);nodeTmp.appendChild(document.createTextNode(strtmparray[1]));newFrag.appendChild(nodeTmp);break;case"href":var nodeTmp=document.createElement("a");nodeTmp.className='LaTeXMathML';nodeTmp.href=strtmparray[1];nodeTmp.appendChild(document.createTextNode(strtmparray[2]));newFrag.appendChild(nodeTmp);break;case"url":var nodeTmp=document.createElement("a");nodeTmp.className='LaTeXMathML';nodeTmp.href=strtmparray[1];nodeTmp.appendChild(document.createTextNode(strtmparray[1]));newFrag.appendChild(nodeTmp);break;case"figure":var nodeTmp=document.createElement("table");nodeTmp.className='figure';var FIGtbody=document.createElement("tbody");var FIGlbl=strtmparray[1].match(/\\label\s*\{\s*(\w+)\s*\}/);strtmparray[1]=strtmparray[1].replace(/\\label\s*\{\w+\}/g,"");var capIndex=strtmparray[1].search(/\\caption\s*\{[\s\S]+\}/);var FIGcap="";if(capIndex>=0){var tmp=strtmparray[1];var delimcnt=0;var capstart=-1;for(var pos=capIndex;pos<tmp.length;pos++){if(tmp.charAt(pos)=="{"){delimcnt++};if(tmp.charAt(pos)=="}"){delimcnt--};if(delimcnt==1&&capstart<0){capstart=pos+1};if(delimcnt==0&&capstart>0){capend=pos-1;FIGcap=tmp.substring(capstart,pos);break}}}
-var FIGtr2=document.createElement("tr");var FIGtd2=document.createElement("td");FIGtd2.className="caption";var FIGanchor=document.createElement("a");FIGanchor.className="figure";if(FIGlbl!=null){FIGanchor.id=FIGlbl[1];}
-LaTeXCounter["figure"]++;var fignmbr=makeNumberString(LaTeXCounter["figure"]);var anchorSpan=document.createElement("span");anchorSpan.className="figure";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(fignmbr));FIGanchor.appendChild(anchorSpan);FIGtd2.appendChild(FIGanchor);var FIGspan=document.createElement("span");FIGspan.className="figure";FIGspan.appendChild(document.createTextNode("Figure "+fignmbr+". "));FIGtd2.appendChild(FIGspan);FIGtd2.appendChild(document.createTextNode(""+FIGcap));FIGtr2.appendChild(FIGtd2);FIGtbody.appendChild(FIGtr2);var IsSpecial=false;var FIGinfo=strtmparray[1].match(/\\includegraphics\s*\{([^\}]+)\}/);if(FIGinfo==null){FIGinfo=strtmparray[1].match(/\\includegraphics\s*\[[^\]]*\]\s*\{\s*([^\}]+)\s*\}/);}
-if(FIGinfo==null){FIGinfo=strtmparray[1].match(/\\special\s*\{\s*([^\}]+)\}/);IsSpecial=true};if(FIGinfo!=null){var FIGtr1=document.createElement("tr");var FIGtd1=document.createElement("td");FIGtd1.className="image";var FIGimg=document.createElement("img");var FIGsrc=FIGinfo[1];FIGimg.src=FIGsrc;FIGimg.alt="Figure "+FIGsrc+" did not load";FIGimg.title="Figure "+fignmbr+". "+FIGcap;FIGimg.id="figure"+fignmbr;FIGtd1.appendChild(FIGimg);FIGtr1.appendChild(FIGtd1);FIGtbody.appendChild(FIGtr1);}
-nodeTmp.appendChild(FIGtbody);newFrag.appendChild(nodeTmp);break;case"table":var nodeTmp=document.createElement("table");if(strtmparray[1].search(/\\centering/)>=0){nodeTmp.className='LaTeXtable centered';nodeTmp.align="center";}else{nodeTmp.className='LaTeXtable';};tableid++;nodeTmp.id="LaTeXtable"+tableid;var TABlbl=strtmparray[1].match(/\\label\s*\{\s*(\w+)\s*\}/);strtmparray[1]=strtmparray[1].replace(/\\label\s*\{\w+\}/g,"");var capIndex=strtmparray[1].search(/\\caption\s*\{[\s\S]+\}/);var TABcap="";if(capIndex>=0){var tmp=strtmparray[1];var delimcnt=0;var capstart=-1;for(var pos=capIndex;pos<tmp.length;pos++){if(tmp.charAt(pos)=="{"){delimcnt++};if(tmp.charAt(pos)=="}"){delimcnt--};if(delimcnt==1&&capstart<0){capstart=pos+1};if(delimcnt==0&&capstart>0){capend=pos-1;TABcap=tmp.substring(capstart,pos);break}}}
-if(TABcap!=""){var TABtbody=document.createElement("tbody");var TABcaption=document.createElement("caption");TABcaption.className="LaTeXtable centered";var TABanchor=document.createElement("a");TABanchor.className="LaTeXtable";if(TABlbl!=null){TABanchor.id=TABlbl[1];}
-LaTeXCounter["table"]++;var tabnmbr=makeNumberString(LaTeXCounter["table"]);var anchorSpan=document.createElement("span");anchorSpan.className="LaTeXtable";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(tabnmbr));TABanchor.appendChild(anchorSpan);TABcaption.appendChild(TABanchor);var TABspan=document.createElement("span");TABspan.className="LaTeXtable";TABspan.appendChild(document.createTextNode("Table "+tabnmbr+". "));TABcaption.appendChild(TABspan);TABcaption.appendChild(document.createTextNode(""+TABcap));nodeTmp.appendChild(TABcaption);}
-var TABinfo=strtmparray[1].match(/\\begin\s*\{\s*tabular\s*\}([\s\S]+)\\end\s*\{\s*tabular\s*\}/);if(TABinfo!=null){var TABtbody=document.createElement('tbody');var TABrow=null;var TABcell=null;var row=0;var col=0;var TABalign=TABinfo[1].match(/^\s*\{([^\}]+)\}/);TABinfo=TABinfo[1].replace(/^\s*\{[^\}]+\}/,"");TABinfo=TABinfo.replace(/\\hline/g,"");TABalign[1]=TABalign[1].replace(/\|/g,"");TABalign[1]=TABalign[1].replace(/\s/g,"");TABinfo=TABinfo.split("\\\\");for(row=0;row<TABinfo.length;row++){TABrow=document.createElement("tr");TABinfo[row]=TABinfo[row].split("&");for(col=0;col<TABinfo[row].length;col++){TABcell=document.createElement("td");switch(TABalign[1].charAt(col)){case"l":TABcell.align="left";break;case"c":TABcell.align="center";break;case"r":TABcell.align="right";break;default:TABcell.align="left";};TABcell.appendChild(document.createTextNode(TABinfo[row][col]));TABrow.appendChild(TABcell);}
-TABtbody.appendChild(TABrow);}
-nodeTmp.appendChild(TABtbody);}
-newFrag.appendChild(nodeTmp);break;case"logicalbreak":var nodeTmp=document.createElement("p");nodeTmp.className=strtmparray[1];nodeTmp.appendChild(document.createTextNode("\u00A0"));newFrag.appendChild(nodeTmp);break;case"appendix":inAppendix=true;sectionCntr=0;break;case"alistitem":var EndDiv=document.createElement("div");EndDiv.className="endlistitem";newFrag.appendChild(EndDiv);var BegDiv=document.createElement("div");BegDiv.className="listitem";if(strtmparray[1]!=" "){var BegSpan=document.createElement("span");BegSpan.className="listitemmarker";var boldBegSpan=document.createElement("b");boldBegSpan.appendChild(document.createTextNode(strtmparray[1]+" "));BegSpan.appendChild(boldBegSpan);BegDiv.appendChild(BegSpan);}
-newFrag.appendChild(BegDiv);break;case"br":newFrag.appendChild(document.createElement("br"));break;case"bibitem":newFrag.appendChild(document.createElement("br"));var nodeTmp=document.createElement("a");nodeTmp.className='bibitem';var nodeSpan=document.createElement("span");nodeSpan.className='bibitem';bibcntr++;var lbl=strtmparray[1].match(/\{\s*(\w+)\s*\}/);strtmparray[1]=strtmparray[1].replace(/\s*\{\s*\w+\s*\}/g,"");strtmparray[1]=strtmparray[1].replace(/^\s*\[/,"");strtmparray[1]=strtmparray[1].replace(/\s*\]$/,"");strtmparray[1]=strtmparray[1].replace(/^\s+|\s+$/g,"");if(lbl==null){biblist[bibcntr]="bibitem"+bibcntr}else{biblist[bibcntr]=lbl[1];};nodeTmp.name=biblist[bibcntr];nodeTmp.id=biblist[bibcntr];if(strtmparray[1]!=""){nodeSpan.appendChild(document.createTextNode(strtmparray[1]));}else{nodeSpan.appendChild(document.createTextNode("["+bibcntr+"]"));}
-nodeTmp.appendChild(nodeSpan);newFrag.appendChild(nodeTmp);break;case"cite":var nodeTmp=document.createElement("a");nodeTmp.className='cite';nodeTmp.name='cite';nodeTmp.href="#"+strtmparray[1];newFrag.appendChild(nodeTmp);break;case"ref":var nodeTmp=document.createElement("a");nodeTmp.className='ref';nodeTmp.name='ref';nodeTmp.href="#"+strtmparray[1];newFrag.appendChild(nodeTmp);break;default:var nodeTmp=document.createElement("div");nodeTmp.className=strtmparray[0];if(IsCounter.test(strtmparray[0])){LaTeXCounter[strtmparray[0]]++;var nodeAnchor=document.createElement("a");nodeAnchor.className=strtmparray[0];var divnum=makeNumberString(LaTeXCounter[strtmparray[0]]);var anchorSpan=document.createElement("span");anchorSpan.className=strtmparray[0];anchorSpan.appendChild(document.createTextNode(divnum));anchorSpan.style.display="none";nodeAnchor.appendChild(anchorSpan);nodeTmp.appendChild(nodeAnchor);var nodeSpan=document.createElement("span");nodeSpan.className=strtmparray[0];nodeSpan.appendChild(document.createTextNode(strtmparray[1]+" "+divnum+". "));nodeTmp.appendChild(nodeSpan);}
-if(isIE){if(strtmparray[0]==("thebibliography"||"abstract"||"keyword"||"proof")){var nodeSpan=document.createElement("span");nodeSpan.className=strtmparray[0];nodeSpan.appendChild(document.createTextNode(strtmparray[1]));nodeTmp.appendChild(nodeSpan);}}
-if(strtmparray[0]=="endenumerate"||strtmparray[0]=="enditemize"||strtmparray[0]=="enddescription"){var endDiv=document.createElement("div");endDiv.className="endlistitem";newFrag.appendChild(endDiv);}
-newFrag.appendChild(nodeTmp);if(strtmparray[0]=="enumerate"||strtmparray[0]=="itemize"||strtmparray[0]=="description"){var endDiv=document.createElement("div");endDiv.className="listitem";newFrag.appendChild(endDiv);}}}else{strtmp[j]=strtmp[j].replace(/\\\$/g,"<per>");strtmp[j]=strtmp[j].replace(/\$([^\$]+)\$/g," \\[$1\\[ ");strtmp[j]=strtmp[j].replace(/<per>/g,"\\$");strtmp[j]=strtmp[j].replace(/\\begin\s*\{\s*math\s*\}([\s\S]+?)\\end\s*\{\s*math\s*\}/g," \\[$1\\[ ");var strtmptmp=strtmp[j].split("\\[");for(var jjj=0;jjj<strtmptmp.length;jjj++){if(jjj%2){var nodeTmp=document.createElement("span");nodeTmp.className='inlinemath';nodeTmp.appendChild(document.createTextNode("$"+strtmptmp[jjj]+"$"));newFrag.appendChild(nodeTmp);}else{var TagIndex=strtmptmp[jjj].search(/\\\w+/);var tmpIndex=TagIndex;while(tmpIndex>-1){if(/^\\textcolor/.test(strtmptmp[jjj].substring(TagIndex,strtmptmp[jjj].length))){strtmptmp[jjj]=strtmptmp[jjj].replace(/\\textcolor\s*\{\s*(\w+)\s*\}\s*/," \\[textcolor\\]$1\\]|");}else{if(/^\\colorbox/.test(strtmptmp[jjj].substring(TagIndex,strtmptmp[jjj].length))){strtmptmp[jjj]=strtmptmp[jjj].replace(/\\colorbox\s*\{\s*(\w+)\s*\}\s*/," \\[colorbox\\]$1\\]|");}else{strtmptmp[jjj]=strtmptmp[jjj].substring(0,TagIndex)+strtmptmp[jjj].substring(TagIndex,strtmptmp[jjj].length).replace(/\\\s*(\w+)\s*/," \\[$1\\]|");}}
-TagIndex+=strtmptmp[jjj].substring(TagIndex,strtmptmp[jjj].length).search(/\|/);TagIndex++;strtmptmp[jjj]=strtmptmp[jjj].replace(/\\\]\|/,"\\] ");if(strtmptmp[jjj].charAt(TagIndex)=="{"){strtmptmp[jjj]=strtmptmp[jjj].substring(0,TagIndex)+strtmptmp[jjj].substring(TagIndex+1,strtmptmp[jjj].length);var delimcnt=1;for(var kk=TagIndex;kk<strtmptmp[jjj].length;kk++){if(strtmptmp[jjj].charAt(kk)=="{"){delimcnt++};if(strtmptmp[jjj].charAt(kk)=="}"){delimcnt--};if(delimcnt==0){break;}}
-strtmptmp[jjj]=strtmptmp[jjj].substring(0,kk)+"\\[ "+strtmptmp[jjj].substring(kk+1,strtmptmp[jjj].length);TagIndex=kk+3;}else{strtmptmp[jjj]=strtmptmp[jjj].substring(0,TagIndex)+"\\[ "+strtmptmp[jjj].substring(TagIndex+1,strtmptmp[jjj].length);TagIndex=TagIndex+3;}
-if(TagIndex<strtmptmp[jjj].length){tmpIndex=strtmptmp[jjj].substring(TagIndex,strtmptmp[jjj].length).search(/\\\w+/);}
-else{tmpIndex=-1};TagIndex+=tmpIndex;}
-strtmptmp[jjj]=strtmptmp[jjj].replace(/\\\\\s*\\\\/g,"\\\\");strtmptmp[jjj]=strtmptmp[jjj].replace(/\\\\/g," \\[br\\] \\[ ");strtmptmp[jjj]=strtmptmp[jjj].replace(/\\label\s*\{\s*(\w+)\s*\}/g," \\[a\\]$1\\[ ");var strlbls=strtmptmp[jjj].split("\\[");for(var jj=0;jj<strlbls.length;jj++){if(jj%2){var strtmparray=strlbls[jj].split("\\]");switch(strtmparray[0]){case"textcolor":var nodeTmp=document.createElement("span");nodeTmp.className='LaTeXColor';if(IsColorName.test(strtmparray[1].toLowerCase())){nodeTmp.style.color=LaTeXColor[strtmparray[1].toLowerCase()];}else{nodeTmp.style.color=strtmparray[1];};nodeTmp.appendChild(document.createTextNode(strtmparray[2]));newFrag.appendChild(nodeTmp);break;case"colorbox":var nodeTmp=document.createElement("span");nodeTmp.className='LaTeXColor';if(IsColorName.test(strtmparray[1].toLowerCase())){nodeTmp.style.background=LaTeXColor[strtmparray[1].toLowerCase()];}else{nodeTmp.style.background=strtmparray[1];};nodeTmp.appendChild(document.createTextNode(strtmparray[2]));newFrag.appendChild(nodeTmp);break;case"br":newFrag.appendChild(document.createElement("br"));break;case"a":var nodeTmp=document.createElement("a");nodeTmp.className='LaTeXMathMLlabel';nodeTmp.id=strtmparray[1];nodeTmp.style.display="none";newFrag.appendChild(nodeTmp);break;default:var nodeTmp=document.createElement("span");nodeTmp.className=strtmparray[0];nodeTmp.appendChild(document.createTextNode(strtmparray[1]))
-newFrag.appendChild(nodeTmp);}}else{newFrag.appendChild(document.createTextNode(strlbls[jj]));}}}}}}}};TheBody.parentNode.replaceChild(newFrag,TheBody);}}}
-return TheBody;}
-function LaTeXDivsAndRefs(thebody){var TheBody=thebody;var EndDivClass=null;var AllDivs=TheBody.getElementsByTagName("div");var lbl2id="";var lblnode=null;for(var i=AllDivs.length-1;i>=0;i--){EndDivClass=AllDivs[i].className.match(/end\w+/);if(EndDivClass!=null){EndDivClass=EndDivClass[0];var DivClass=EndDivClass.substring(3,EndDivClass.length);var EndDivNode=AllDivs[i];break;}}
-while(EndDivClass!=null){var newFrag=document.createDocumentFragment();var RootNode=EndDivNode.parentNode;var ClassCount=1;while(EndDivNode.previousSibling!=null&&ClassCount>0){switch(EndDivNode.previousSibling.className){case EndDivClass:ClassCount++;newFrag.insertBefore(EndDivNode.previousSibling,newFrag.firstChild);break;case DivClass:if(EndDivNode.previousSibling.nodeName=="DIV"){ClassCount--;if(lbl2id!=""){EndDivNode.previousSibling.id=lbl2id;lbl2id=""}
-if(ClassCount==0){RootNode=EndDivNode.previousSibling;}else{newFrag.insertBefore(EndDivNode.previousSibling,newFrag.firstChild);}};break;case'LaTeXMathMLlabel':lbl2id=EndDivNode.previousSibling.id;EndDivNode.parentNode.removeChild(EndDivNode.previousSibling);break;default:newFrag.insertBefore(EndDivNode.previousSibling,newFrag.firstChild);}}
-RootNode.appendChild(newFrag);EndDivNode.parentNode.removeChild(EndDivNode);AllDivs=TheBody.getElementsByTagName("DIV");for(i=AllDivs.length-1;i>=0;i--){EndDivClass=AllDivs[i].className.match(/end\w+/);if(EndDivClass!=null){ClassCount=0;EndDivClass=EndDivClass[0];DivClass=EndDivClass.substring(3,EndDivClass.length);EndDivNode=AllDivs[i];RootNode=EndDivNode.parentNode;break;}}}
-var AllDivs=TheBody.getElementsByTagName("div");var DIV2LI=null;for(var i=0;i<AllDivs.length;i++){if(AllDivs[i].className=="itemize"||AllDivs[i].className=="enumerate"||AllDivs[i].className=="description"){if(AllDivs[i].className=="itemize"){RootNode=document.createElement("UL");}else{RootNode=document.createElement("OL");}
-RootNode.className='LaTeXMathML';if(AllDivs[i].hasChildNodes()){AllDivs[i].removeChild(AllDivs[i].firstChild)};while(AllDivs[i].hasChildNodes()){if(AllDivs[i].firstChild.hasChildNodes()){DIV2LI=document.createElement("LI");while(AllDivs[i].firstChild.hasChildNodes()){DIV2LI.appendChild(AllDivs[i].firstChild.firstChild);}
-if(DIV2LI.firstChild.className=="listitemmarker"){DIV2LI.style.listStyleType="none";}
-RootNode.appendChild(DIV2LI)}
-AllDivs[i].removeChild(AllDivs[i].firstChild);}
-AllDivs[i].appendChild(RootNode);}}
-var AllAnchors=TheBody.getElementsByTagName("a");for(var i=0;i<AllAnchors.length;i++){if(AllAnchors[i].className=="ref"||AllAnchors[i].className=="cite"){var label=AllAnchors[i].href.match(/\#(\w+)/);if(label!=null){var labelNode=document.getElementById(label[1]);if(labelNode!=null){var TheSpans=labelNode.getElementsByTagName("SPAN");if(TheSpans!=null){var refNode=TheSpans[0].cloneNode(true);refNode.style.display="inline"
-refNode.className=AllAnchors[i].className;AllAnchors[i].appendChild(refNode);}}}}}
-return TheBody;}
-var AMbody;var AMnoMathML=false,AMtranslated=false;function translate(spanclassAM){if(!AMtranslated){AMtranslated=true;AMinitSymbols();var LaTeXContainers=[];var AllContainers=document.getElementsByTagName('*');var ExtendName="";for(var k=0,l=0;k<AllContainers.length;k++){ExtendName=" "+AllContainers[k].className+" ";if(ExtendName.match(/\sLaTeX\s/)!=null){LaTeXContainers[l]=AllContainers[k];l++;}};if(LaTeXContainers.length>0){for(var m=0;m<LaTeXContainers.length;m++){AMbody=LaTeXContainers[m];try{AMbody=LaTeXDivsAndRefs(LaTeXpreProcess(AMbody));}catch(err){alert("Unknown Error: Defaulting to Original LaTeXMathML");}
-if(AMbody.tagName=="PRE"){var PreChilds=document.createDocumentFragment();var DivChilds=document.createElement("DIV");while(AMbody.hasChildNodes()){DivChilds.appendChild(AMbody.firstChild);}
-PreChilds.appendChild(DivChilds);AMbody.parentNode.replaceChild(PreChilds,AMbody);AMbody=DivChilds;}
-AMprocessNode(AMbody,false,spanclassAM);}}else{AMbody=document.getElementsByTagName("body")[0];try{AMbody=LaTeXDivsAndRefs(LaTeXpreProcess(AMbody));}catch(err){alert("Unknown Error: Defaulting to Original LaTeXMathML");}
-AMprocessNode(AMbody,false,spanclassAM);}}}
-if(isIE){document.write("<object id=\"mathplayer\" classid=\"clsid:32F66A20-7614-11D4-BD11-00104BD3F987\"></object>");document.write("<?import namespace=\"m\" implementation=\"#mathplayer\"?>");}
-function generic()
-{translate();};if(typeof window.addEventListener!='undefined')
-{window.addEventListener('load',generic,false);}
-else if(typeof document.addEventListener!='undefined')
-{document.addEventListener('load',generic,false);}
-else if(typeof window.attachEvent!='undefined')
-{window.attachEvent('onload',generic);}
-else
-{if(typeof window.onload=='function')
-{var existing=onload;window.onload=function()
-{existing();generic();};}
-else
-{window.onload=generic;}}
diff --git a/data/bash_completion.tpl b/data/bash_completion.tpl
--- a/data/bash_completion.tpl
+++ b/data/bash_completion.tpl
@@ -4,7 +4,7 @@
 
 _pandoc()
 {
-    local cur prev opts lastc informats outformats datadir
+    local cur prev opts lastc informats outformats datafiles
     COMPREPLY=()
     cur="${COMP_WORDS[COMP_CWORD]}"
     prev="${COMP_WORDS[COMP_CWORD-1]}"
@@ -14,7 +14,7 @@
     informats="%s"
     outformats="%s"
     highlight_styles="%s"
-    datadir="%s"
+    datafiles="%s"
 
     case "${prev}" in
          --from|-f|--read|-r)
@@ -34,7 +34,7 @@
              return 0
              ;;
          --print-default-data-file)
-             COMPREPLY=( $(compgen -W "reference.odt reference.docx $(find ${datadir} | sed -e 's/.*\/data\///')" -- ${cur}) )
+             COMPREPLY=( $(compgen -W "${datafiles}" -- ${cur}) )
              return 0
              ;;
          --wrap)
diff --git a/data/pptx/docProps/thumbnail.jpeg b/data/pptx/docProps/thumbnail.jpeg
deleted file mode 100644
Binary files a/data/pptx/docProps/thumbnail.jpeg and /dev/null differ
diff --git a/data/templates/default.latex b/data/templates/default.latex
--- a/data/templates/default.latex
+++ b/data/templates/default.latex
@@ -7,10 +7,19 @@
 $endif$$endif$%
 \documentclass[$if(fontsize)$$fontsize$,$endif$$if(lang)$$babel-lang$,$endif$$if(papersize)$$papersize$paper,$endif$$if(beamer)$ignorenonframetext,$if(handout)$handout,$endif$$if(aspectratio)$aspectratio=$aspectratio$,$endif$$endif$$for(classoption)$$classoption$$sep$,$endfor$]{$documentclass$}
 $if(beamer)$
+$if(background-image)$
+\usebackgroundtemplate{%
+\includegraphics[width=\paperwidth]{$background-image$}%
+}
+$endif$
+\usepackage{pgfpages}
 \setbeamertemplate{caption}[numbered]
 \setbeamertemplate{caption label separator}{: }
 \setbeamercolor{caption name}{fg=normal text.fg}
 \beamertemplatenavigationsymbols$if(navigation)$$navigation$$else$empty$endif$
+$for(beameroption)$
+\setbeameroption{$beameroption$}
+$endfor$
 $endif$
 $if(beamerarticle)$
 \usepackage{beamerarticle} % needs to be loaded first
diff --git a/data/templates/default.ms b/data/templates/default.ms
--- a/data/templates/default.ms
+++ b/data/templates/default.ms
@@ -90,7 +90,10 @@
 $author$
 $endfor$
 $if(date)$
-.ND "$date$"
+.AU
+.sp 0.5
+.ft R
+$date$
 $endif$
 $if(abstract)$
 .AB
diff --git a/data/templates/default.revealjs b/data/templates/default.revealjs
--- a/data/templates/default.revealjs
+++ b/data/templates/default.revealjs
@@ -197,6 +197,11 @@
 $if(parallaxBackgroundImage)$
         // Parallax background image
         parallaxBackgroundImage: '$parallaxBackgroundImage$', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'"
+$else$
+$if(background-image)$
+       // Parallax background image
+       parallaxBackgroundImage: '$background-image$', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'"
+$endif$
 $endif$
 $if(parallaxBackgroundSize)$
         // Parallax background size
diff --git a/man/pandoc.1 b/man/pandoc.1
--- a/man/pandoc.1
+++ b/man/pandoc.1
@@ -1,5 +1,5 @@
 .\"t
-.TH PANDOC 1 "March 17, 2018" "pandoc 2.1.3"
+.TH PANDOC 1 "April 26, 2018" "pandoc 2.2"
 .SH NAME
 pandoc - general markup converter
 .SH SYNOPSIS
@@ -10,34 +10,21 @@
 Pandoc is a Haskell library for converting from one markup format to
 another, and a command\-line tool that uses this library.
 .PP
-Pandoc can read Markdown, CommonMark, PHP Markdown Extra,
-GitHub\-Flavored Markdown, MultiMarkdown, and (subsets of) Textile,
-reStructuredText, HTML, LaTeX, MediaWiki markup, TWiki markup, TikiWiki
-markup, Creole 1.0, Haddock markup, OPML, Emacs Org mode, DocBook, JATS,
-Muse, txt2tags, Vimwiki, EPUB, ODT, and Word docx.
-.PP
-Pandoc can write plain text, Markdown, CommonMark, PHP Markdown Extra,
-GitHub\-Flavored Markdown, MultiMarkdown, reStructuredText, XHTML,
-HTML5, LaTeX (including \f[C]beamer\f[] slide shows), ConTeXt, RTF,
-OPML, DocBook, JATS, OpenDocument, ODT, Word docx, GNU Texinfo,
-MediaWiki markup, DokuWiki markup, ZimWiki markup, Haddock markup, EPUB
-(v2 or v3), FictionBook2, Textile, groff man, groff ms, Emacs Org mode,
-AsciiDoc, InDesign ICML, TEI Simple, Muse, PowerPoint slide shows and
-Slidy, Slideous, DZSlides, reveal.js or S5 HTML slide shows.
-It can also produce PDF output on systems where LaTeX, ConTeXt,
-\f[C]pdfroff\f[], \f[C]wkhtmltopdf\f[], \f[C]prince\f[], or
-\f[C]weasyprint\f[] is installed.
+Pandoc can convert between numerous markup and word processing formats,
+including, but not limited to, various flavors of Markdown, HTML, LaTeX
+and Word docx.
+For the full lists of input and output formats, see the
+\f[C]\-\-from\f[] and \f[C]\-\-to\f[] options below.
+Pandoc can also produce PDF output: see creating a PDF, below.
 .PP
 Pandoc\[aq]s enhanced version of Markdown includes syntax for tables,
-definition lists, metadata blocks, \f[C]Div\f[] blocks, footnotes and
-citations, embedded LaTeX (including math), Markdown inside HTML block
-elements, and much more.
-These enhancements, described further under Pandoc\[aq]s Markdown, can
-be disabled using the \f[C]markdown_strict\f[] format.
+definition lists, metadata blocks, footnotes, citations, math, and much
+more.
+See below under Pandoc\[aq]s Markdown.
 .PP
 Pandoc has a modular design: it consists of a set of readers, which
 parse text in a given format and produce a native representation of the
-document (like an \f[I]abstract syntax tree\f[] or AST), and a set of
+document (an \f[I]abstract syntax tree\f[] or AST), and a set of
 writers, which convert this native representation into a target format.
 Thus, adding an input or output format requires only adding a reader or
 writer.
@@ -229,69 +216,184 @@
 .TP
 .B \f[C]\-f\f[] \f[I]FORMAT\f[], \f[C]\-r\f[] \f[I]FORMAT\f[], \f[C]\-\-from=\f[]\f[I]FORMAT\f[], \f[C]\-\-read=\f[]\f[I]FORMAT\f[]
 Specify input format.
-\f[I]FORMAT\f[] can be \f[C]native\f[] (native Haskell), \f[C]json\f[]
-(JSON version of native AST), \f[C]markdown\f[] (pandoc\[aq]s extended
-Markdown), \f[C]markdown_strict\f[] (original unextended Markdown),
-\f[C]markdown_phpextra\f[] (PHP Markdown Extra), \f[C]markdown_mmd\f[]
-(MultiMarkdown), \f[C]gfm\f[] (GitHub\-Flavored Markdown),
-\f[C]commonmark\f[] (CommonMark Markdown), \f[C]textile\f[] (Textile),
-\f[C]rst\f[] (reStructuredText), \f[C]html\f[] (HTML), \f[C]docbook\f[]
-(DocBook), \f[C]t2t\f[] (txt2tags), \f[C]docx\f[] (docx), \f[C]odt\f[]
-(ODT), \f[C]epub\f[] (EPUB), \f[C]opml\f[] (OPML), \f[C]org\f[] (Emacs
-Org mode), \f[C]mediawiki\f[] (MediaWiki markup), \f[C]twiki\f[] (TWiki
-markup), \f[C]tikiwiki\f[] (TikiWiki markup), \f[C]creole\f[] (Creole
-1.0), \f[C]haddock\f[] (Haddock markup), or \f[C]latex\f[] (LaTeX).
-(\f[C]markdown_github\f[] provides deprecated and less accurate support
-for Github\-Flavored Markdown; please use \f[C]gfm\f[] instead, unless
-you need to use extensions other than \f[C]smart\f[].) Extensions can be
-individually enabled or disabled by appending \f[C]+EXTENSION\f[] or
-\f[C]\-EXTENSION\f[] to the format name.
+\f[I]FORMAT\f[] can be:
+.RS
+.IP \[bu] 2
+\f[C]commonmark\f[] (CommonMark Markdown)
+.IP \[bu] 2
+\f[C]creole\f[] (Creole 1.0)
+.IP \[bu] 2
+\f[C]docbook\f[] (DocBook)
+.IP \[bu] 2
+\f[C]docx\f[] (Word docx)
+.IP \[bu] 2
+\f[C]epub\f[] (EPUB)
+.IP \[bu] 2
+\f[C]fb2\f[] (FictionBook2 e\-book)
+.IP \[bu] 2
+\f[C]gfm\f[] (GitHub\-Flavored Markdown), or \f[C]markdown_github\f[],
+which provides deprecated and less accurate support for Github\-Flavored
+Markdown; please use \f[C]gfm\f[] instead, unless you need to use
+extensions other than \f[C]smart\f[].
+.IP \[bu] 2
+\f[C]haddock\f[] (Haddock markup)
+.IP \[bu] 2
+\f[C]html\f[] (HTML)
+.IP \[bu] 2
+\f[C]jats\f[] (JATS XML)
+.IP \[bu] 2
+\f[C]json\f[] (JSON version of native AST)
+.IP \[bu] 2
+\f[C]latex\f[] (LaTeX)
+.IP \[bu] 2
+\f[C]markdown\f[] (Pandoc\[aq]s Markdown)
+.IP \[bu] 2
+\f[C]markdown_mmd\f[] (MultiMarkdown)
+.IP \[bu] 2
+\f[C]markdown_phpextra\f[] (PHP Markdown Extra)
+.IP \[bu] 2
+\f[C]markdown_strict\f[] (original unextended Markdown)
+.IP \[bu] 2
+\f[C]mediawiki\f[] (MediaWiki markup)
+.IP \[bu] 2
+\f[C]muse\f[] (Muse)
+.IP \[bu] 2
+\f[C]native\f[] (native Haskell)
+.IP \[bu] 2
+\f[C]odt\f[] (ODT)
+.IP \[bu] 2
+\f[C]opml\f[] (OPML)
+.IP \[bu] 2
+\f[C]org\f[] (Emacs Org mode)
+.IP \[bu] 2
+\f[C]rst\f[] (reStructuredText)
+.IP \[bu] 2
+\f[C]t2t\f[] (txt2tags)
+.IP \[bu] 2
+\f[C]textile\f[] (Textile)
+.IP \[bu] 2
+\f[C]tikiwiki\f[] (TikiWiki markup)
+.IP \[bu] 2
+\f[C]twiki\f[] (TWiki markup)
+.IP \[bu] 2
+\f[C]vimwiki\f[] (Vimwiki)
+.PP
+Extensions can be individually enabled or disabled by appending
+\f[C]+EXTENSION\f[] or \f[C]\-EXTENSION\f[] to the format name.
 See Extensions below, for a list of extensions and their names.
 See \f[C]\-\-list\-input\-formats\f[] and \f[C]\-\-list\-extensions\f[],
 below.
-.RS
 .RE
 .TP
 .B \f[C]\-t\f[] \f[I]FORMAT\f[], \f[C]\-w\f[] \f[I]FORMAT\f[], \f[C]\-\-to=\f[]\f[I]FORMAT\f[], \f[C]\-\-write=\f[]\f[I]FORMAT\f[]
 Specify output format.
-\f[I]FORMAT\f[] can be \f[C]native\f[] (native Haskell), \f[C]json\f[]
-(JSON version of native AST), \f[C]plain\f[] (plain text),
-\f[C]markdown\f[] (pandoc\[aq]s extended Markdown),
-\f[C]markdown_strict\f[] (original unextended Markdown),
-\f[C]markdown_phpextra\f[] (PHP Markdown Extra), \f[C]markdown_mmd\f[]
-(MultiMarkdown), \f[C]gfm\f[] (GitHub\-Flavored Markdown),
-\f[C]commonmark\f[] (CommonMark Markdown), \f[C]rst\f[]
-(reStructuredText), \f[C]html4\f[] (XHTML 1.0 Transitional),
-\f[C]html\f[] or \f[C]html5\f[] (HTML5/XHTML polyglot markup),
-\f[C]latex\f[] (LaTeX), \f[C]beamer\f[] (LaTeX beamer slide show),
-\f[C]context\f[] (ConTeXt), \f[C]man\f[] (groff man), \f[C]mediawiki\f[]
-(MediaWiki markup), \f[C]dokuwiki\f[] (DokuWiki markup),
-\f[C]zimwiki\f[] (ZimWiki markup), \f[C]textile\f[] (Textile),
-\f[C]org\f[] (Emacs Org mode), \f[C]texinfo\f[] (GNU Texinfo),
-\f[C]opml\f[] (OPML), \f[C]docbook\f[] or \f[C]docbook4\f[] (DocBook 4),
-\f[C]docbook5\f[] (DocBook 5), \f[C]jats\f[] (JATS XML),
-\f[C]opendocument\f[] (OpenDocument), \f[C]odt\f[] (OpenOffice text
-document), \f[C]docx\f[] (Word docx), \f[C]haddock\f[] (Haddock markup),
-\f[C]rtf\f[] (rich text format), \f[C]epub2\f[] (EPUB v2 book),
-\f[C]epub\f[] or \f[C]epub3\f[] (EPUB v3), \f[C]fb2\f[] (FictionBook2
-e\-book), \f[C]asciidoc\f[] (AsciiDoc), \f[C]icml\f[] (InDesign ICML),
-\f[C]tei\f[] (TEI Simple), \f[C]slidy\f[] (Slidy HTML and JavaScript
-slide show), \f[C]slideous\f[] (Slideous HTML and JavaScript slide
-show), \f[C]dzslides\f[] (DZSlides HTML5 + JavaScript slide show),
-\f[C]revealjs\f[] (reveal.js HTML5 + JavaScript slide show), \f[C]s5\f[]
-(S5 HTML and JavaScript slide show), \f[C]pptx\f[] (PowerPoint slide
-show) or the path of a custom lua writer (see Custom writers, below).
-(\f[C]markdown_github\f[] provides deprecated and less accurate support
-for Github\-Flavored Markdown; please use \f[C]gfm\f[] instead, unless
-you use extensions that do not work with \f[C]gfm\f[].) Note that
-\f[C]odt\f[], \f[C]docx\f[], and \f[C]epub\f[] output will not be
-directed to \f[I]stdout\f[] unless forced with \f[C]\-o\ \-\f[].
+\f[I]FORMAT\f[] can be:
+.RS
+.IP \[bu] 2
+\f[C]asciidoc\f[] (AsciiDoc)
+.IP \[bu] 2
+\f[C]beamer\f[] (LaTeX beamer slide show)
+.IP \[bu] 2
+\f[C]commonmark\f[] (CommonMark Markdown)
+.IP \[bu] 2
+\f[C]context\f[] (ConTeXt)
+.IP \[bu] 2
+\f[C]docbook\f[] or \f[C]docbook4\f[] (DocBook 4)
+.IP \[bu] 2
+\f[C]docbook5\f[] (DocBook 5)
+.IP \[bu] 2
+\f[C]docx\f[] (Word docx)
+.IP \[bu] 2
+\f[C]dokuwiki\f[] (DokuWiki markup)
+.IP \[bu] 2
+\f[C]epub\f[] or \f[C]epub3\f[] (EPUB v3 book)
+.IP \[bu] 2
+\f[C]epub2\f[] (EPUB v2)
+.IP \[bu] 2
+\f[C]fb2\f[] (FictionBook2 e\-book)
+.IP \[bu] 2
+\f[C]gfm\f[] (GitHub\-Flavored Markdown), or \f[C]markdown_github\f[],
+which provides deprecated and less accurate support for Github\-Flavored
+Markdown; please use \f[C]gfm\f[] instead, unless you use extensions
+that do not work with \f[C]gfm\f[].
+.IP \[bu] 2
+\f[C]haddock\f[] (Haddock markup)
+.IP \[bu] 2
+\f[C]html\f[] or \f[C]html5\f[] (HTML, i.e.
+HTML5/XHTML polyglot markup)
+.IP \[bu] 2
+\f[C]html4\f[] (XHTML 1.0 Transitional)
+.IP \[bu] 2
+\f[C]icml\f[] (InDesign ICML)
+.IP \[bu] 2
+\f[C]jats\f[] (JATS XML)
+.IP \[bu] 2
+\f[C]json\f[] (JSON version of native AST)
+.IP \[bu] 2
+\f[C]latex\f[] (LaTeX)
+.IP \[bu] 2
+\f[C]man\f[] (groff man)
+.IP \[bu] 2
+\f[C]markdown\f[] (Pandoc\[aq]s Markdown)
+.IP \[bu] 2
+\f[C]markdown_mmd\f[] (MultiMarkdown)
+.IP \[bu] 2
+\f[C]markdown_phpextra\f[] (PHP Markdown Extra)
+.IP \[bu] 2
+\f[C]markdown_strict\f[] (original unextended Markdown)
+.IP \[bu] 2
+\f[C]mediawiki\f[] (MediaWiki markup)
+.IP \[bu] 2
+\f[C]ms\f[] (groff ms)
+.IP \[bu] 2
+\f[C]muse\f[] (Muse),
+.IP \[bu] 2
+\f[C]native\f[] (native Haskell),
+.IP \[bu] 2
+\f[C]odt\f[] (OpenOffice text document)
+.IP \[bu] 2
+\f[C]opml\f[] (OPML)
+.IP \[bu] 2
+\f[C]opendocument\f[] (OpenDocument)
+.IP \[bu] 2
+\f[C]org\f[] (Emacs Org mode)
+.IP \[bu] 2
+\f[C]plain\f[] (plain text),
+.IP \[bu] 2
+\f[C]pptx\f[] (PowerPoint slide show)
+.IP \[bu] 2
+\f[C]rst\f[] (reStructuredText)
+.IP \[bu] 2
+\f[C]rtf\f[] (Rich Text Format)
+.IP \[bu] 2
+\f[C]texinfo\f[] (GNU Texinfo)
+.IP \[bu] 2
+\f[C]textile\f[] (Textile)
+.IP \[bu] 2
+\f[C]slideous\f[] (Slideous HTML and JavaScript slide show)
+.IP \[bu] 2
+\f[C]slidy\f[] (Slidy HTML and JavaScript slide show)
+.IP \[bu] 2
+\f[C]dzslides\f[] (DZSlides HTML5 + JavaScript slide show),
+.IP \[bu] 2
+\f[C]revealjs\f[] (reveal.js HTML5 + JavaScript slide show)
+.IP \[bu] 2
+\f[C]s5\f[] (S5 HTML and JavaScript slide show)
+.IP \[bu] 2
+\f[C]tei\f[] (TEI Simple)
+.IP \[bu] 2
+\f[C]zimwiki\f[] (ZimWiki markup)
+.IP \[bu] 2
+the path of a custom lua writer, see Custom writers below
+.PP
+Note that \f[C]odt\f[], \f[C]docx\f[], and \f[C]epub\f[] output will not
+be directed to \f[I]stdout\f[] unless forced with \f[C]\-o\ \-\f[].
+.PP
 Extensions can be individually enabled or disabled by appending
 \f[C]+EXTENSION\f[] or \f[C]\-EXTENSION\f[] to the format name.
 See Extensions below, for a list of extensions and their names.
 See \f[C]\-\-list\-output\-formats\f[] and
 \f[C]\-\-list\-extensions\f[], below.
-.RS
 .RE
 .TP
 .B \f[C]\-o\f[] \f[I]FILE\f[], \f[C]\-\-output=\f[]\f[I]FILE\f[]
@@ -532,19 +634,29 @@
 return\ {{Str\ =\ expand_hello_world}}
 \f[]
 .fi
+.PP
+In order of preference, pandoc will look for lua filters in
+.IP "1." 3
+a specified full or relative path (executable or non\-executable)
+.IP "2." 3
+\f[C]$DATADIR/filters\f[] (executable or non\-executable) where
+\f[C]$DATADIR\f[] is the user data directory (see
+\f[C]\-\-data\-dir\f[], above).
 .RE
 .TP
 .B \f[C]\-M\f[] \f[I]KEY\f[][\f[C]=\f[]\f[I]VAL\f[]], \f[C]\-\-metadata=\f[]\f[I]KEY\f[][\f[C]:\f[]\f[I]VAL\f[]]
 Set the metadata field \f[I]KEY\f[] to the value \f[I]VAL\f[].
 A value specified on the command line overrides a value specified in the
-document.
+document using [YAML metadata
+blocks][Extension:\f[C]yaml_metadata_block\f[]].
 Values will be parsed as YAML boolean or string values.
 If no value is specified, the value will be treated as Boolean true.
 Like \f[C]\-\-variable\f[], \f[C]\-\-metadata\f[] causes template
 variables to be set.
 But unlike \f[C]\-\-variable\f[], \f[C]\-\-metadata\f[] affects the
 metadata of the underlying document (which is accessible from filters
-and may be printed in some output formats).
+and may be printed in some output formats) and metadata values will be
+escaped when inserted into the template.
 .RS
 .RE
 .TP
@@ -852,8 +964,9 @@
 .TP
 .B \f[C]\-\-ascii\f[]
 Use only ASCII characters in output.
-Currently supported only for HTML and DocBook output (which uses
-numerical entities instead of UTF\-8 when this option is selected).
+Currently supported for XML and HTML formats (which use numerical
+entities instead of UTF\-8 when this option is selected) and for groff
+ms and man (which use hexadecimal escapes).
 .RS
 .RE
 .TP
@@ -1300,60 +1413,6 @@
 Note that this option does not imply \f[C]\-\-katex\f[].
 .RS
 .RE
-.TP
-.B \f[C]\-m\f[] [\f[I]URL\f[]], \f[C]\-\-latexmathml\f[][\f[C]=\f[]\f[I]URL\f[]]
-\f[I]Deprecated.\f[] Use the LaTeXMathML script to display embedded TeX
-math in HTML output.
-TeX math will be displayed between \f[C]$\f[] or \f[C]$$\f[] characters
-and put in \f[C]<span>\f[] tags with class \f[C]LaTeX\f[].
-The LaTeXMathML JavaScript will then change it to MathML.
-Note that currently only Firefox and Safari (and select e\-book readers)
-natively support MathML.
-To insert a link the \f[C]LaTeXMathML.js\f[] script, provide a
-\f[I]URL\f[].
-.RS
-.RE
-.TP
-.B \f[C]\-\-jsmath\f[][\f[C]=\f[]\f[I]URL\f[]]
-\f[I]Deprecated.\f[] Use jsMath (the predecessor of MathJax) to display
-embedded TeX math in HTML output.
-TeX math will be put inside \f[C]<span>\f[] tags (for inline math) or
-\f[C]<div>\f[] tags (for display math) with class \f[C]math\f[] and
-rendered by the jsMath script.
-The \f[I]URL\f[] should point to the script (e.g.
-\f[C]jsMath/easy/load.js\f[]); if provided, it will be linked to in the
-header of standalone HTML documents.
-If a \f[I]URL\f[] is not provided, no link to the jsMath load script
-will be inserted; it is then up to the author to provide such a link in
-the HTML template.
-.RS
-.RE
-.TP
-.B \f[C]\-\-gladtex\f[]
-\f[I]Deprecated.\f[] Enclose TeX math in \f[C]<eq>\f[] tags in HTML
-output.
-The resulting HTML can then be processed by gladTeX to produce images of
-the typeset formulas and an HTML file with links to these images.
-So, the procedure is:
-.RS
-.IP
-.nf
-\f[C]
-pandoc\ \-s\ \-\-gladtex\ input.md\ \-o\ myfile.htex
-gladtex\ \-d\ myfile\-images\ myfile.htex
-#\ produces\ myfile.html\ and\ images\ in\ myfile\-images
-\f[]
-.fi
-.RE
-.TP
-.B \f[C]\-\-mimetex\f[][\f[C]=\f[]\f[I]URL\f[]]
-\f[I]Deprecated.\f[] Render TeX math using the mimeTeX CGI script, which
-generates an image for each TeX formula.
-This should work in all browsers.
-If \f[I]URL\f[] is not specified, it is assumed that the script is at
-\f[C]/cgi\-bin/mimetex.cgi\f[].
-.RS
-.RE
 .SS Options for wrapper scripts
 .TP
 .B \f[C]\-\-dump\-args\f[]
@@ -1419,23 +1478,25 @@
 For \f[C]pdf\f[] output, customize the \f[C]default.latex\f[] template
 (or the \f[C]default.context\f[] template, if you use
 \f[C]\-t\ context\f[], or the \f[C]default.ms\f[] template, if you use
-\f[C]\-t\ ms\f[], or the \f[C]default.html5\f[] template, if you use
-\f[C]\-t\ html5\f[]).
+\f[C]\-t\ ms\f[], or the \f[C]default.html\f[] template, if you use
+\f[C]\-t\ html\f[]).
 .IP \[bu] 2
 \f[C]docx\f[] has no template (however, you can use
 \f[C]\-\-reference\-doc\f[] to customize the output).
 .PP
 Templates contain \f[I]variables\f[], which allow for the inclusion of
 arbitrary information at any point in the file.
-Variables may be set within the document using YAML metadata blocks.
-They may also be set at the command line using the
-\f[C]\-V/\-\-variable\f[] option: variables set in this way override
-metadata fields with the same name.
+They may be set at the command line using the \f[C]\-V/\-\-variable\f[]
+option.
+If a variable is not set, pandoc will look for the key in the
+document\[aq]s metadata \[en] which can be set using either [YAML
+metadata blocks][Extension:\f[C]yaml_metadata_block\f[]] or with the
+\f[C]\-\-metadata\f[] option.
 .SS Variables set by pandoc
 .PP
 Some variables are set automatically by pandoc.
-These vary somewhat depending on the output format, but include metadata
-fields as well as the following:
+These vary somewhat depending on the output format, but include the
+following:
 .TP
 .B \f[C]sourcefile\f[], \f[C]outputfile\f[]
 source and destination filenames, as given on the command line.
@@ -1678,6 +1739,11 @@
 .RS
 .RE
 .TP
+.B \f[C]beameroption\f[]
+In beamer, add extra beamer option with \f[C]\\setbeameroption{}\f[]
+.RS
+.RE
+.TP
 .B \f[C]geometry\f[]
 option for \f[C]geometry\f[] package, e.g.
 \f[C]margin=1in\f[]; may be repeated for multiple options
@@ -2359,7 +2425,7 @@
 writes HTML with the Haskell code in bird tracks, so it can be copied
 and pasted as literate Haskell source.
 .PP
-Note that GHC expects the bird tracks in the first column, so indentend
+Note that GHC expects the bird tracks in the first column, so indented
 literate code blocks (e.g.
 inside an itemized environment) will not be picked up by the Haskell
 compiler.
@@ -2377,8 +2443,7 @@
 .RE
 .TP
 .B output formats
-\f[C]markdown\f[], \f[C]docx\f[], \f[C]odt\f[], \f[C]opendocument\f[],
-\f[C]html\f[]
+\f[C]docx\f[], \f[C]odt\f[], \f[C]opendocument\f[], \f[C]html\f[]
 .RS
 .RE
 .SS Extension: \f[C]styles\f[]
@@ -3772,7 +3837,8 @@
 .nf
 \f[C]
 header\-includes:
-\-\ ```{=latex}
+\-\ |
+\ \ ```{=latex}
 \ \ \\let\\oldsection\\section
 \ \ \\renewcommand{\\section}[1]{\\clearpage\\oldsection{#1}}
 \ \ ```
@@ -4194,9 +4260,29 @@
 \f[]
 .fi
 .PP
+This can be useful to insert raw xml into \f[C]docx\f[] documents, e.g.
+a pagebreak:
+.IP
+.nf
+\f[C]
+```{=openxml}
+<w:p>
+\ \ <w:r>
+\ \ \ \ <w:br\ w:type="page"/>
+\ \ </w:r>
+</w:p>
+```
+\f[]
+.fi
+.PP
 The format name should match the target format name (see
 \f[C]\-t/\-\-to\f[], above, for a list, or use
 \f[C]pandoc\ \-\-list\-output\-formats\f[]).
+Use \f[C]openxml\f[] for \f[C]docx\f[] output, \f[C]opendocument\f[] for
+\f[C]odt\f[] output, \f[C]html5\f[] for \f[C]epub3\f[] output,
+\f[C]html4\f[] for \f[C]epub2\f[] output, and \f[C]latex\f[],
+\f[C]beamer\f[], \f[C]ms\f[], or \f[C]html5\f[] for \f[C]pdf\f[] output
+(depending on what you use for \f[C]\-\-pdf\-engine\f[]).
 .PP
 This extension presupposes that the relevant kind of inline code or
 fenced code block is enabled.
diff --git a/pandoc.cabal b/pandoc.cabal
--- a/pandoc.cabal
+++ b/pandoc.cabal
@@ -1,5 +1,5 @@
 name:            pandoc
-version:         2.1.3
+version:         2.2
 cabal-version:   >= 1.10
 build-type:      Custom
 license:         GPL-2
@@ -19,11 +19,11 @@
                  (subsets of) HTML, reStructuredText, LaTeX, DocBook, JATS,
                  MediaWiki markup, TWiki markup, TikiWiki markup, Creole 1.0,
                  Haddock markup, OPML, Emacs Org-Mode, Emacs Muse, txt2tags,
-                 Vimwiki, Word Docx, ODT, and Textile, and it can write
-                 Markdown, reStructuredText, XHTML, HTML 5, LaTeX, ConTeXt,
-                 DocBook, JATS, OPML, TEI, OpenDocument, ODT, Word docx,
-                 RTF, MediaWiki, DokuWiki, ZimWiki, Textile, groff man,
-                 groff ms, plain text, Emacs Org-Mode, AsciiDoc,
+                 Vimwiki, Word Docx, ODT, EPUB, FictionBook2, and Textile,
+                 and it can write Markdown, reStructuredText, XHTML, HTML 5,
+                 LaTeX, ConTeXt, DocBook, JATS, OPML, TEI, OpenDocument,
+                 ODT, Word docx, RTF, MediaWiki, DokuWiki, ZimWiki, Textile,
+                 groff man, groff ms, plain text, Emacs Org-Mode, AsciiDoc,
                  Haddock markup, EPUB (v2 and v3), FictionBook2, InDesign
                  ICML, Muse, LaTeX beamer slides, PowerPoint, and several
                  kinds of HTML/JavaScript slide shows (S5, Slidy, Slideous,
@@ -102,7 +102,6 @@
                  data/odt/META-INF/manifest.xml
                  -- source files for reference.pptx
                  data/pptx/_rels/.rels
-                 data/pptx/docProps/thumbnail.jpeg
                  data/pptx/docProps/app.xml
                  data/pptx/docProps/core.xml
                  data/pptx/ppt/slideLayouts/_rels/slideLayout1.xml.rels
@@ -149,8 +148,6 @@
                  data/pptx/[Content_Types].xml
                   -- stylesheet for EPUB writer
                  data/epub.css
-                 -- data for LaTeXMathML writer
-                 data/LaTeXMathML.js
                  -- data for dzslides writer
                  data/dzslides/template.html
                  -- default abbreviations file
@@ -304,6 +301,8 @@
                  test/fb2/images-embedded.html
                  test/fb2/images-embedded.fb2
                  test/fb2/test-small.png
+                 test/fb2/reader/*.fb2
+                 test/fb2/reader/*.native
                  test/fb2/test.jpg
                  test/docx/*.docx
                  test/docx/golden/*.docx
@@ -371,7 +370,7 @@
                  zlib >= 0.5 && < 0.7,
                  skylighting >= 0.5.1 && < 0.8,
                  data-default >= 0.4 && < 0.8,
-                 temporary >= 1.1 && < 1.3,
+                 temporary >= 1.1 && < 1.4,
                  blaze-html >= 0.9 && < 0.10,
                  blaze-markup >= 0.8 && < 0.9,
                  yaml >= 0.8.8.2 && < 0.9,
@@ -448,6 +447,7 @@
                    Text.Pandoc.Readers.Odt,
                    Text.Pandoc.Readers.EPUB,
                    Text.Pandoc.Readers.Muse,
+                   Text.Pandoc.Readers.FB2,
                    Text.Pandoc.Writers,
                    Text.Pandoc.Writers.Native,
                    Text.Pandoc.Writers.Docbook,
@@ -599,7 +599,7 @@
      hs-source-dirs: prelude
      other-modules:  Prelude
      build-depends:  base-compat >= 0.9
-  ghc-options:   -rtsopts -Wall -fno-warn-unused-do-bind
+  ghc-options:   -rtsopts -Wall -fno-warn-unused-do-bind -threaded
   default-language: Haskell2010
   other-extensions: NoImplicitPrelude
 
@@ -618,7 +618,7 @@
                   filepath >= 1.1 && < 1.5,
                   hslua >= 0.9.5 && < 0.9.6,
                   process >= 1.2.3 && < 1.7,
-                  temporary >= 1.1 && < 1.3,
+                  temporary >= 1.1 && < 1.4,
                   Diff >= 0.2 && < 0.4,
                   tasty >= 0.11 && < 1.1,
                   tasty-hunit >= 0.9 && < 0.11,
@@ -666,6 +666,7 @@
                   Tests.Readers.EPUB
                   Tests.Readers.Muse
                   Tests.Readers.Creole
+                  Tests.Readers.FB2
                   Tests.Writers.Native
                   Tests.Writers.ConTeXt
                   Tests.Writers.Docbook
@@ -702,6 +703,6 @@
      hs-source-dirs: prelude
      other-modules:  Prelude
      build-depends:  base-compat >= 0.9
-  ghc-options:   -rtsopts -Wall -fno-warn-unused-do-bind
+  ghc-options:   -rtsopts -Wall -fno-warn-unused-do-bind -threaded
   default-language: Haskell2010
   other-extensions: NoImplicitPrelude
diff --git a/src/Text/Pandoc/App.hs b/src/Text/Pandoc/App.hs
--- a/src/Text/Pandoc/App.hs
+++ b/src/Text/Pandoc/App.hs
@@ -52,7 +52,7 @@
 import Data.Aeson.TH (deriveJSON)
 import qualified Data.ByteString as BS
 import qualified Data.ByteString.Lazy as B
-import Data.Char (toLower, toUpper)
+import Data.Char (toLower, toUpper, isAscii, ord)
 import Data.List (find, intercalate, isPrefixOf, isSuffixOf, sort)
 import qualified Data.Map as M
 import Data.Maybe (fromMaybe, isJust, isNothing)
@@ -66,7 +66,12 @@
 import qualified Data.Yaml as Yaml
 import GHC.Generics
 import Network.URI (URI (..), parseURI)
+#ifdef EMBED_DATA_FILES
+import Text.Pandoc.Data (dataFiles)
+#else
+import System.Directory (getDirectoryContents)
 import Paths_pandoc (getDataDir)
+#endif
 import Data.Aeson.Encode.Pretty (encodePretty', Config(..), keyOrder,
          defConfig, Indent(..), NumberFormat(..))
 import Skylighting (Style, Syntax (..), defaultSyntaxMap, parseTheme,
@@ -352,12 +357,6 @@
         maybe return (addStringAsVariable "epub-cover-image")
                      (optEpubCoverImage opts)
         >>=
-        (\vars -> case optHTMLMathMethod opts of
-                       LaTeXMathML Nothing -> do
-                          s <- UTF8.toString <$> readDataFile "LaTeXMathML.js"
-                          return $ ("mathml-script", s) : vars
-                       _ -> return vars)
-        >>=
         (\vars ->  if format == "dzslides"
                       then do
                           dztempl <- UTF8.toString <$> readDataFile
@@ -514,16 +513,19 @@
                 let htmlFormat = format `elem`
                       ["html","html4","html5","s5","slidy",
                        "slideous","dzslides","revealjs"]
-                    handleEntities = if (htmlFormat ||
-                                         format == "docbook4" ||
-                                         format == "docbook5" ||
-                                         format == "docbook") && optAscii opts
-                                     then toEntities
-                                     else id
+                    escape
+                      | optAscii opts
+                      , htmlFormat || format == "docbook4" ||
+                        format == "docbook5" || format == "docbook" ||
+                        format == "jats" || format == "opml" ||
+                        format == "icml" = toEntities
+                      | optAscii opts
+                      , format == "ms" || format == "man" = groffEscape
+                      | otherwise = id
                     addNl = if standalone
                                then id
                                else (<> T.singleton '\n')
-                output <- (addNl . handleEntities) <$> f writerOptions doc
+                output <- (addNl . escape) <$> f writerOptions doc
                 writerFn eol outputFile =<<
                   if optSelfContained opts && htmlFormat
                      -- TODO not maximally efficient; change type
@@ -531,6 +533,12 @@
                      then T.pack <$> makeSelfContained (T.unpack output)
                      else return output
 
+groffEscape :: Text -> Text
+groffEscape = T.concatMap toUchar
+  where toUchar c
+         | isAscii c = T.singleton c
+         | otherwise = T.pack $ printf "\\[u%04X]" (ord c)
+
 type Transform = Pandoc -> Pandoc
 
 isTextFormat :: String -> Bool
@@ -730,6 +738,7 @@
     ".odt"      -> "odt"
     ".pdf"      -> "pdf"  -- so we get an "unknown reader" error
     ".doc"      -> "doc"  -- so we get an "unknown reader" error
+    ".fb2"      -> "fb2"
     _           -> defaultReaderName fallback xs
 
 -- Determine default writer based on output file extension
@@ -1396,40 +1405,6 @@
                   "URL")
                   "" -- Use KaTeX for HTML Math
 
-    , Option "m" ["latexmathml", "asciimathml"]
-                 (OptArg
-                  (\arg opt -> do
-                      deprecatedOption "--latexmathml, --asciimathml, -m" ""
-                      return opt { optHTMLMathMethod = LaTeXMathML arg })
-                  "URL")
-                 "" -- "Use LaTeXMathML script in html output"
-
-    , Option "" ["mimetex"]
-                 (OptArg
-                  (\arg opt -> do
-                      deprecatedOption "--mimetex" ""
-                      let url' = case arg of
-                                      Just u  -> u ++ "?"
-                                      Nothing -> "/cgi-bin/mimetex.cgi?"
-                      return opt { optHTMLMathMethod = WebTeX url' })
-                  "URL")
-                 "" -- "Use mimetex for HTML math"
-
-    , Option "" ["jsmath"]
-                 (OptArg
-                  (\arg opt -> do
-                      deprecatedOption "--jsmath" ""
-                      return opt { optHTMLMathMethod = JsMath arg})
-                  "URL")
-                 "" -- "Use jsMath for HTML math"
-
-    , Option "" ["gladtex"]
-                 (NoArg
-                  (\opt -> do
-                      deprecatedOption "--gladtex" ""
-                      return opt { optHTMLMathMethod = GladTeX }))
-                 "" -- "Use gladtex for HTML math"
-
     , Option "" ["abbreviations"]
                 (ReqArg
                  (\arg opt -> return opt { optAbbreviations = Just arg })
@@ -1475,7 +1450,7 @@
     , Option "" ["bash-completion"]
                  (NoArg
                   (\_ -> do
-                     ddir <- getDataDir
+                     datafiles <- getDataFileNames
                      tpl <- runIOorExplode $
                               UTF8.toString <$>
                                 readDefaultDataFile "bash_completion.tpl"
@@ -1487,7 +1462,7 @@
                          (unwords readersNames)
                          (unwords writersNames)
                          (unwords $ map fst highlightingStyles)
-                         ddir
+                         (unwords datafiles)
                      exitSuccess ))
                  "" -- "Print bash completion script"
 
@@ -1560,6 +1535,16 @@
                  "" -- "Show help"
 
     ]
+
+getDataFileNames :: IO [FilePath]
+getDataFileNames = do
+#ifdef EMBED_DATA_FILES
+  let allDataFiles = map fst dataFiles
+#else
+  allDataFiles <- filter (\x -> x /= "." && x /= "..") <$>
+                      (getDataDir >>= getDirectoryContents)
+#endif
+  return $ "reference.docx" : "reference.odt" : "reference.pptx" : allDataFiles
 
 -- Returns usage message
 usageMessage :: String -> [OptDescr (Opt -> IO Opt)] -> String
diff --git a/src/Text/Pandoc/Class.hs b/src/Text/Pandoc/Class.hs
--- a/src/Text/Pandoc/Class.hs
+++ b/src/Text/Pandoc/Class.hs
@@ -855,7 +855,7 @@
 writeMedia dir mediabag subpath = do
   -- we join and split to convert a/b/c to a\b\c on Windows;
   -- in zip containers all paths use /
-  let fullpath = dir </> normalise subpath
+  let fullpath = dir </> unEscapeString (normalise subpath)
   let mbcontents = lookupMedia subpath mediabag
   case mbcontents of
        Nothing -> throwError $ PandocResourceNotFound subpath
diff --git a/src/Text/Pandoc/Extensions.hs b/src/Text/Pandoc/Extensions.hs
--- a/src/Text/Pandoc/Extensions.hs
+++ b/src/Text/Pandoc/Extensions.hs
@@ -345,6 +345,10 @@
                                           [Ext_smart,
                                            Ext_latex_macros,
                                            Ext_auto_identifiers]
+getDefaultExtensions "beamer"          = extensionsFromList
+                                          [Ext_smart,
+                                           Ext_latex_macros,
+                                           Ext_auto_identifiers]
 getDefaultExtensions "context"         = extensionsFromList
                                           [Ext_smart,
                                            Ext_auto_identifiers]
diff --git a/src/Text/Pandoc/MIME.hs b/src/Text/Pandoc/MIME.hs
--- a/src/Text/Pandoc/MIME.hs
+++ b/src/Text/Pandoc/MIME.hs
@@ -174,7 +174,7 @@
            ,("eml","message/rfc822")
            ,("ent","chemical/x-ncbi-asn1-ascii")
            ,("eot","application/vnd.ms-fontobject")
-           ,("eps","application/postscript")
+           ,("eps","application/eps")
            ,("etx","text/x-setext")
            ,("exe","application/x-msdos-program")
            ,("ez","application/andrew-inset")
diff --git a/src/Text/Pandoc/Options.hs b/src/Text/Pandoc/Options.hs
--- a/src/Text/Pandoc/Options.hs
+++ b/src/Text/Pandoc/Options.hs
@@ -106,9 +106,6 @@
 data EPUBVersion = EPUB2 | EPUB3 deriving (Eq, Show, Read, Data, Typeable, Generic)
 
 data HTMLMathMethod = PlainMath
-                    | LaTeXMathML (Maybe String)  -- url of LaTeXMathML.js
-                    | JsMath (Maybe String)       -- url of jsMath load script
-                    | GladTeX
                     | WebTeX String               -- url of TeX->image script.
                     | MathML
                     | MathJax String              -- url of MathJax.js
diff --git a/src/Text/Pandoc/PDF.hs b/src/Text/Pandoc/PDF.hs
--- a/src/Text/Pandoc/PDF.hs
+++ b/src/Text/Pandoc/PDF.hs
@@ -51,7 +51,7 @@
 import System.Exit (ExitCode (..))
 import System.FilePath
 import System.IO (stdout)
-import System.IO.Temp (withTempDirectory, withTempFile)
+import System.IO.Temp (withTempDirectory)
 #if MIN_VERSION_base(4,8,3)
 import System.IO.Error (IOError, isDoesNotExistError)
 #else
@@ -130,9 +130,11 @@
   verbosity <- getVerbosity
   liftIO $ ms2pdf verbosity args source
 makePDF program pdfargs writer opts doc = do
-  let withTemp = if takeBaseName program == "context"
-                    then withTempDirectory "."
-                    else withTempDir
+  -- With context and latex, we create a temp directory within
+  -- the working directory, since pdflatex sometimes tries to
+  -- use tools like epstopdf.pl, which are restricted if run
+  -- on files outside the working directory.
+  let withTemp = withTempDirectory "."
   commonState <- getCommonState
   verbosity <- getVerbosity
   liftIO $ withTemp "tex2pdf." $ \tmpdir -> do
@@ -173,6 +175,8 @@
     Just "image/png" -> doNothing
     Just "image/jpeg" -> doNothing
     Just "application/pdf" -> doNothing
+    -- Note: eps is converted by pdflatex using epstopdf.pl
+    Just "application/eps" -> doNothing
     Just "image/svg+xml" -> E.catch (do
       (exit, _) <- pipeProcess Nothing "rsvg-convert"
                      ["-f","pdf","-a","-o",pdfOut,fname] BL.empty
@@ -277,7 +281,12 @@
     let file' = file
 #endif
     let programArgs = ["-halt-on-error", "-interaction", "nonstopmode",
-         "-output-directory", tmpDir'] ++ args ++ [file']
+         "-output-directory", tmpDir'] ++
+         -- see #4484, only compress images on last run:
+         if program == "xelatex" && runNumber < numRuns
+            then ["-output-driver", "xdvipdfmx -z0"]
+            else []
+         ++ args ++ [file']
     env' <- getEnvironment
     let sep = [searchPathSeparator]
     let texinputs = maybe (tmpDir' ++ sep) ((tmpDir' ++ sep) ++)
@@ -363,43 +372,44 @@
       baseTag = TagOpen "base"
         [("href", T.pack cwd <> T.singleton pathSeparator)] : [TagText "\n"]
       source = renderTags $ hd ++ baseTag ++ tl
-  pdfFile <- withTempFile "." "html2pdf.pdf" $ \fp _ -> return fp
-  let pdfFileArgName = ["-o" | program == "prince"]
-  let programArgs = args ++ ["-"] ++ pdfFileArgName ++ [pdfFile]
-  env' <- getEnvironment
-  when (verbosity >= INFO) $ do
-    putStrLn "[makePDF] Command line:"
-    putStrLn $ program ++ " " ++ unwords (map show programArgs)
-    putStr "\n"
-    putStrLn "[makePDF] Environment:"
-    mapM_ print env'
-    putStr "\n"
-    putStrLn "[makePDF] Contents of intermediate HTML:"
-    TextIO.putStr source
-    putStr "\n"
-  (exit, out) <- E.catch
-    (pipeProcess (Just env') program programArgs $ BL.fromStrict $ UTF8.fromText source)
-    (\(e :: IOError) -> if isDoesNotExistError e
-                           then E.throwIO $
-                                  PandocPDFProgramNotFoundError program
-                           else E.throwIO e)
-  when (verbosity >= INFO) $ do
-    BL.hPutStr stdout out
-    putStr "\n"
-  pdfExists <- doesFileExist pdfFile
-  mbPdf <- if pdfExists
-            -- We read PDF as a strict bytestring to make sure that the
-            -- temp directory is removed on Windows.
-            -- See https://github.com/jgm/pandoc/issues/1192.
-            then do
-              res <- (Just . BL.fromChunks . (:[])) `fmap` BS.readFile pdfFile
-              removeFile pdfFile
-              return res
-            else return Nothing
-  return $ case (exit, mbPdf) of
-             (ExitFailure _, _)      -> Left out
-             (ExitSuccess, Nothing)  -> Left ""
-             (ExitSuccess, Just pdf) -> Right pdf
+  withTempDir "html2pdf.pdf" $ \tmpdir -> do
+    let pdfFile = tmpdir </> "out.pdf"
+    let pdfFileArgName = ["-o" | program == "prince"]
+    let programArgs = args ++ ["-"] ++ pdfFileArgName ++ [pdfFile]
+    env' <- getEnvironment
+    when (verbosity >= INFO) $ do
+      putStrLn "[makePDF] Command line:"
+      putStrLn $ program ++ " " ++ unwords (map show programArgs)
+      putStr "\n"
+      putStrLn "[makePDF] Environment:"
+      mapM_ print env'
+      putStr "\n"
+      putStrLn "[makePDF] Contents of intermediate HTML:"
+      TextIO.putStr source
+      putStr "\n"
+    (exit, out) <- E.catch
+      (pipeProcess (Just env') program programArgs $ BL.fromStrict $ UTF8.fromText source)
+      (\(e :: IOError) -> if isDoesNotExistError e
+                             then E.throwIO $
+                                    PandocPDFProgramNotFoundError program
+                             else E.throwIO e)
+    when (verbosity >= INFO) $ do
+      BL.hPutStr stdout out
+      putStr "\n"
+    pdfExists <- doesFileExist pdfFile
+    mbPdf <- if pdfExists
+              -- We read PDF as a strict bytestring to make sure that the
+              -- temp directory is removed on Windows.
+              -- See https://github.com/jgm/pandoc/issues/1192.
+              then do
+                res <- (Just . BL.fromChunks . (:[])) `fmap` BS.readFile pdfFile
+                removeFile pdfFile
+                return res
+              else return Nothing
+    return $ case (exit, mbPdf) of
+               (ExitFailure _, _)      -> Left out
+               (ExitSuccess, Nothing)  -> Left ""
+               (ExitSuccess, Just pdf) -> Right pdf
 
 context2pdf :: Verbosity    -- ^ Verbosity level
             -> FilePath     -- ^ temp directory for output
diff --git a/src/Text/Pandoc/Parsing.hs b/src/Text/Pandoc/Parsing.hs
--- a/src/Text/Pandoc/Parsing.hs
+++ b/src/Text/Pandoc/Parsing.hs
@@ -135,7 +135,7 @@
                              extractIdClass,
                              insertIncludedFile,
                              insertIncludedFileF,
-                             -- * Re-exports from Text.Pandoc.Parsec
+                             -- * Re-exports from Text.Parsec
                              Stream,
                              runParser,
                              runParserT,
@@ -532,15 +532,15 @@
           map char romanDigits
     thousands <- ((1000 *) . length) <$> many thousand
     ninehundreds <- option 0 $ try $ hundred >> thousand >> return 900
-    fivehundreds <- ((500 *) . length) <$> many fivehundred
+    fivehundreds <- option 0 $ 500 <$ fivehundred
     fourhundreds <- option 0 $ try $ hundred >> fivehundred >> return 400
     hundreds <- ((100 *) . length) <$> many hundred
     nineties <- option 0 $ try $ ten >> hundred >> return 90
-    fifties <- ((50 *) . length) <$> many fifty
+    fifties <- option 0 $ (50 <$ fifty)
     forties <- option 0 $ try $ ten >> fifty >> return 40
     tens <- ((10 *) . length) <$> many ten
     nines <- option 0 $ try $ one >> ten >> return 9
-    fives <- ((5 *) . length) <$> many five
+    fives <- option 0 $ (5 <$ five)
     fours <- option 0 $ try $ one >> five >> return 4
     ones <- length <$> many one
     let total = thousands + ninehundreds + fivehundreds + fourhundreds +
@@ -593,7 +593,7 @@
   -- http://en.wikipedia.org/wiki/State_of_emergency_(disambiguation)
   -- as a URL, while NOT picking up the closing paren in
   -- (http://wikipedia.org). So we include balanced parens in the URL.
-  let isWordChar c = isAlphaNum c || c `elem` "#$%*+/@\\_-&="
+  let isWordChar c = isAlphaNum c || c `elem` "#$%+/@\\_-&="
   let wordChar = satisfy isWordChar
   let percentEscaped = try $ char '%' >> skipMany1 (satisfy isHexDigit)
   let entity = () <$ characterReference
diff --git a/src/Text/Pandoc/Readers.hs b/src/Text/Pandoc/Readers.hs
--- a/src/Text/Pandoc/Readers.hs
+++ b/src/Text/Pandoc/Readers.hs
@@ -1,7 +1,7 @@
-{-# LANGUAGE NoImplicitPrelude #-}
-{-# LANGUAGE FlexibleInstances   #-}
-{-# LANGUAGE GADTs               #-}
+{-# LANGUAGE MonoLocalBinds      #-}
+{-# LANGUAGE NoImplicitPrelude   #-}
 {-# LANGUAGE ScopedTypeVariables #-}
+
 {-
 Copyright (C) 2006-2018 John MacFarlane <jgm@berkeley.edu>
 
@@ -65,6 +65,7 @@
   , readTxt2Tags
   , readEPUB
   , readMuse
+  , readFB2
   -- * Miscellaneous
   , getReader
   , getDefaultExtensions
@@ -86,6 +87,7 @@
 import Text.Pandoc.Readers.DocBook
 import Text.Pandoc.Readers.Docx
 import Text.Pandoc.Readers.EPUB
+import Text.Pandoc.Readers.FB2
 import Text.Pandoc.Readers.Haddock
 import Text.Pandoc.Readers.HTML (readHtml)
 import Text.Pandoc.Readers.JATS (readJATS)
@@ -143,6 +145,7 @@
            ,("t2t"          , TextReader readTxt2Tags)
            ,("epub"         , ByteStringReader readEPUB)
            ,("muse"         , TextReader readMuse)
+           ,("fb2"          , TextReader readFB2)
            ]
 
 -- | Retrieve reader, extensions based on formatSpec (format+extensions).
diff --git a/src/Text/Pandoc/Readers/DocBook.hs b/src/Text/Pandoc/Readers/DocBook.hs
--- a/src/Text/Pandoc/Readers/DocBook.hs
+++ b/src/Text/Pandoc/Readers/DocBook.hs
@@ -1,5 +1,33 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-# LANGUAGE ExplicitForAll #-}
+{-
+Copyright (C) 2006-2018 John MacFarlane <jgm@berkeley.edu>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+-}
+
+{- |
+   Module      : Text.Pandoc.Readers.DocBook
+   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of DocBook XML to 'Pandoc' document.
+-}
 module Text.Pandoc.Readers.DocBook ( readDocBook ) where
 import Prelude
 import Control.Monad.State.Strict
@@ -237,7 +265,7 @@
 [ ] manvolnum - A reference volume number
 [x] markup - A string of formatting markup in text that is to be
     represented literally
-[ ] mathphrase - A mathematical phrase, an expression that can be represented
+[x] mathphrase - A mathematical phrase, an expression that can be represented
     with ordinary text and a small amount of markup
 [ ] medialabel - A name that identifies the physical medium on which some
     information resides
@@ -699,6 +727,8 @@
         "bibliodiv" -> sect 1
         "biblioentry" -> parseMixed para (elContent e)
         "bibliomixed" -> parseMixed para (elContent e)
+        "equation"         -> para <$> equation e displayMath
+        "informalequation" -> para <$> equation e displayMath
         "glosssee" -> para . (\ils -> text "See " <> ils <> str ".")
                          <$> getInlines e
         "glossseealso" -> para . (\ils -> text "See also " <> ils <> str ".")
@@ -925,9 +955,9 @@
   return $ maybe (text $ map toUpper ref) text $ lookupEntity ref
 parseInline (Elem e) =
   case qName (elName e) of
-        "equation" -> equation displayMath
-        "informalequation" -> equation displayMath
-        "inlineequation" -> equation math
+        "equation" -> equation e displayMath
+        "informalequation" -> equation e displayMath
+        "inlineequation" -> equation e math
         "subscript" -> subscript <$> innerInlines
         "superscript" -> superscript <$> innerInlines
         "inlinemediaobject" -> getMediaobject e
@@ -1006,13 +1036,6 @@
         _          -> innerInlines
    where innerInlines = (trimInlines . mconcat) <$>
                           mapM parseInline (elContent e)
-         equation constructor = return $ mconcat $
-           map (constructor . writeTeX)
-           $ rights
-           $ map (readMathML . showElement . everywhere (mkT removePrefix))
-           $ filterChildren (\x -> qName (elName x) == "math" &&
-                                   qPrefix (elName x) == Just "mml") e
-         removePrefix elname = elname { qPrefix = Nothing }
          codeWithLang = do
            let classes' = case attrValue "language" e of
                                "" -> []
@@ -1050,6 +1073,7 @@
              | not (null xrefLabel) = xrefLabel
              | otherwise            = case qName (elName el) of
                   "chapter"      -> descendantContent "title" el
+                  "section"      -> descendantContent "title" el
                   "sect1"        -> descendantContent "title" el
                   "sect2"        -> descendantContent "title" el
                   "sect3"        -> descendantContent "title" el
@@ -1062,3 +1086,45 @@
             xrefLabel = attrValue "xreflabel" el
             descendantContent name = maybe "???" strContent
                                    . filterElementName (\n -> qName n == name)
+
+-- | Extract a math equation from an element
+--
+-- asciidoc can generate Latex math in CDATA sections.
+--
+-- Note that if some MathML can't be parsed it is silently ignored!
+equation
+  :: Monad m
+  => Element
+  -- ^ The element from which to extract a mathematical equation
+  -> (String -> Inlines)
+  -- ^ A constructor for some Inlines, taking the TeX code as input
+  -> m Inlines
+equation e constructor =
+  return $ mconcat $ map constructor $ mathMLEquations ++ latexEquations
+  where
+    mathMLEquations :: [String]
+    mathMLEquations = map writeTeX $ rights $ readMath
+      (\x -> qName (elName x) == "math" && qPrefix (elName x) == Just "mml")
+      (readMathML . showElement)
+
+    latexEquations :: [String]
+    latexEquations = readMath (\x -> qName (elName x) == "mathphrase")
+                              (concat . fmap showVerbatimCData . elContent)
+
+    readMath :: (Element -> Bool) -> (Element -> b) -> [b]
+    readMath childPredicate fromElement =
+      ( map (fromElement . everywhere (mkT removePrefix))
+      $ filterChildren childPredicate e
+      )
+
+-- | Get the actual text stored in a verbatim CData block. 'showContent'
+-- returns the text still surrounded by the [[CDATA]] tags.
+--
+-- Returns 'showContent' if this is not a verbatim CData
+showVerbatimCData :: Content -> String
+showVerbatimCData (Text (CData CDataVerbatim d _)) = d
+showVerbatimCData c = showContent c
+
+-- | Set the prefix of a name to 'Nothing'
+removePrefix :: QName -> QName
+removePrefix elname = elname { qPrefix = Nothing }
diff --git a/src/Text/Pandoc/Readers/Docx.hs b/src/Text/Pandoc/Readers/Docx.hs
--- a/src/Text/Pandoc/Readers/Docx.hs
+++ b/src/Text/Pandoc/Readers/Docx.hs
@@ -688,6 +688,10 @@
       rowLength :: Row -> Int
       rowLength (Row c) = length c
 
+  -- pad cells.  New Text.Pandoc.Builder will do that for us,
+  -- so this is for compatibility while we switch over.
+  let cells' = map (\row -> take width (row ++ repeat mempty)) cells
+
   hdrCells <- case hdr of
     Just r' -> rowToBlocksList r'
     Nothing -> return $ replicate width mempty
@@ -700,7 +704,7 @@
   let alignments = replicate width AlignDefault
       widths = replicate width 0 :: [Double]
 
-  return $ table caption (zip alignments widths) hdrCells cells
+  return $ table caption (zip alignments widths) hdrCells cells'
 bodyPartToBlocks (OMathPara e) =
   return $ para $ displayMath (writeTeX e)
 
diff --git a/src/Text/Pandoc/Readers/Docx/Combine.hs b/src/Text/Pandoc/Readers/Docx/Combine.hs
--- a/src/Text/Pandoc/Readers/Docx/Combine.hs
+++ b/src/Text/Pandoc/Readers/Docx/Combine.hs
@@ -135,6 +135,10 @@
   | bs' :> BlockQuote bs'' <- viewr (unMany bs)
   , BlockQuote cs'' :< cs' <- viewl (unMany cs) =
       Many $ (bs' |> BlockQuote (bs'' <> cs'')) >< cs'
+  | bs' :> CodeBlock attr codeStr <- viewr (unMany bs)
+  , CodeBlock attr' codeStr' :< cs' <- viewl (unMany cs)
+  , attr == attr' =
+      Many $ (bs' |> CodeBlock attr (codeStr <> "\n" <> codeStr')) >< cs'
 combineBlocks bs cs = bs <> cs
 
 instance (Monoid a, Eq a) => Eq (Modifier a) where
diff --git a/src/Text/Pandoc/Readers/EPUB.hs b/src/Text/Pandoc/Readers/EPUB.hs
--- a/src/Text/Pandoc/Readers/EPUB.hs
+++ b/src/Text/Pandoc/Readers/EPUB.hs
@@ -1,9 +1,36 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE TupleSections     #-}
+{-# LANGUAGE ViewPatterns      #-}
+{-
+Copyright (C) 2014-2018 Matthew Pickering
 
-{-# LANGUAGE TupleSections    #-}
-{-# LANGUAGE ViewPatterns     #-}
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
 
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+-}
+
+{- |
+   Module      : Text.Pandoc.Readers.EPUB
+   Copyright   : Copyright (C) 2014-2018 Matthew Pickering
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of EPUB to 'Pandoc' document.
+-}
+
 module Text.Pandoc.Readers.EPUB
   (readEPUB)
   where
@@ -94,7 +121,7 @@
     mapM_ (uncurry3 insertMedia) (mapMaybe getEntry links)
   where
     getEntry link =
-        let abslink = normalise (root </> link) in
+        let abslink = normalise (unEscapeString (root </> link)) in
         (link , lookup link mimes, ) . fromEntry
           <$> findEntryByPath abslink arc
 
@@ -265,7 +292,7 @@
 findAttrE q e = mkE "findAttr" $ findAttr q e
 
 findEntryByPathE :: PandocMonad m => FilePath -> Archive -> m Entry
-findEntryByPathE (normalise -> path) a =
+findEntryByPathE (normalise . unEscapeString -> path) a =
   mkE ("No entry on path: " ++ path) $ findEntryByPath path a
 
 parseXMLDocE :: PandocMonad m => String -> m Element
diff --git a/src/Text/Pandoc/Readers/FB2.hs b/src/Text/Pandoc/Readers/FB2.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Readers/FB2.hs
@@ -0,0 +1,402 @@
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE TupleSections #-}
+{-
+Copyright (C) 2018 Alexander Krotov <ilabdsf@gmail.com>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+-}
+
+{- |
+   Module      : Text.Pandoc.Readers.FB2
+   Copyright   : Copyright (C) 2018 Alexander Krotov
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Alexander Krotov <ilabdsf@gmail.com>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of FB2 to 'Pandoc' document.
+-}
+
+{-
+
+TODO:
+ - Tables
+ - Named styles
+ - Parse ID attribute for all elements that have it
+
+-}
+
+module Text.Pandoc.Readers.FB2 ( readFB2 ) where
+import Prelude
+import Control.Monad.Except (throwError)
+import Control.Monad.State.Strict
+import Data.ByteString.Lazy.Char8 ( pack )
+import Data.ByteString.Base64.Lazy
+import Data.Char (isSpace, toUpper)
+import Data.List (dropWhileEnd, intersperse)
+import Data.List.Split (splitOn)
+import Data.Text (Text)
+import Data.Default
+import Data.Maybe
+import Text.HTML.TagSoup.Entity (lookupEntity)
+import Text.Pandoc.Builder
+import Text.Pandoc.Class (PandocMonad, insertMedia)
+import Text.Pandoc.Error
+import Text.Pandoc.Options
+import Text.Pandoc.Shared (crFilter)
+import Text.XML.Light
+
+type FB2 m = StateT FB2State m
+
+data FB2State = FB2State{ fb2SectionLevel :: Int
+                        , fb2Meta :: Meta
+                        , fb2Authors :: [String]
+                        } deriving Show
+
+instance Default FB2State where
+  def = FB2State{ fb2SectionLevel = 1
+                , fb2Meta = mempty
+                , fb2Authors = []
+                }
+
+instance HasMeta FB2State where
+  setMeta field v s = s {fb2Meta = setMeta field v (fb2Meta s)}
+  deleteMeta field s = s {fb2Meta = deleteMeta field (fb2Meta s)}
+
+readFB2 :: PandocMonad m => ReaderOptions -> Text -> m Pandoc
+readFB2 _ inp  = do
+  (bs, st) <- runStateT (mapM parseBlock $ parseXML (crFilter inp)) def
+  let authors = if null $ fb2Authors st
+                then id
+                else setMeta "author" (map text $ reverse $ fb2Authors st)
+  pure $ Pandoc (authors $ fb2Meta st) (toList . mconcat $ bs)
+
+-- * Utility functions
+
+trim :: String -> String
+trim = dropWhileEnd isSpace . dropWhile isSpace
+
+removeHash :: String -> String
+removeHash ('#':xs) = xs
+removeHash xs = xs
+
+convertEntity :: String -> String
+convertEntity e = fromMaybe (map toUpper e) (lookupEntity e)
+
+parseInline :: PandocMonad m => Content -> FB2 m Inlines
+parseInline (Elem e) =
+  case qName $ elName e of
+    "strong" -> strong <$> parseStyleType e
+    "emphasis" -> emph <$> parseStyleType e
+    "style" -> parseNamedStyle e
+    "a" -> parseLinkType e
+    "strikethrough" -> strikeout <$> parseStyleType e
+    "sub" -> subscript <$> parseStyleType e
+    "sup" -> superscript <$> parseStyleType e
+    "code" -> pure $ code $ strContent e
+    "image" -> parseInlineImageElement e
+    name -> throwError $ PandocParseError ("Couldn't parse FB2 file: unexpected element " ++ name ++ ".")
+parseInline (Text x) = pure $ text $ cdData x
+parseInline (CRef r) = pure $ str $ convertEntity r
+
+parseSubtitle :: PandocMonad m => Element -> FB2 m Blocks
+parseSubtitle e = headerWith ("", ["unnumbered"], []) <$> gets fb2SectionLevel <*> parsePType e
+
+-- * Root element parser
+
+parseBlock :: PandocMonad m => Content -> FB2 m Blocks
+parseBlock (Elem e) =
+  case qName $ elName e of
+    "?xml"  -> pure mempty
+    "FictionBook" -> mconcat <$> mapM parseFictionBookChild (elChildren e)
+    name -> throwError $ PandocParseError ("Couldn't parse FB2 file: unexpected element " ++ name ++ ".")
+parseBlock _ = pure mempty
+
+-- | Parse a child of @\<FictionBook>@ element.
+parseFictionBookChild :: PandocMonad m => Element -> FB2 m Blocks
+parseFictionBookChild e =
+  case qName $ elName e of
+    "stylesheet" -> pure mempty -- stylesheet is ignored
+    "description" -> mempty <$ mapM_ parseDescriptionChild (elChildren e)
+    "body" -> mconcat <$> mapM parseBodyChild (elChildren e)
+    "binary" -> mempty <$ parseBinaryElement e
+    name -> throwError $ PandocParseError ("Couldn't parse FB2 file: unexpected element " ++ name ++ "in FictionBook.")
+
+-- | Parse a child of @\<description>@ element.
+parseDescriptionChild :: PandocMonad m => Element -> FB2 m ()
+parseDescriptionChild e =
+  case qName $ elName e of
+    "title-info" -> mapM_ parseTitleInfoChild (elChildren e)
+    "src-title-info" -> pure () -- ignore
+    "document-info" -> pure ()
+    "publish-info" -> pure ()
+    "custom-info" -> pure ()
+    "output" -> pure ()
+    name -> throwError $ PandocParseError ("Couldn't parse FB2 file: unexpected element " ++ name ++ "in description.")
+
+-- | Parse a child of @\<body>@ element.
+parseBodyChild :: PandocMonad m => Element -> FB2 m Blocks
+parseBodyChild e =
+  case qName $ elName e of
+    "image" -> parseImageElement e
+    "title" -> header <$> gets fb2SectionLevel <*> parseTitleType (elContent e)
+    "epigraph" -> parseEpigraph e
+    "section" -> parseSection e
+    name -> throwError $ PandocParseError ("Couldn't parse FB2 file: unexpected element " ++ name ++ " in body.")
+
+-- | Parse a @\<binary>@ element.
+parseBinaryElement :: PandocMonad m => Element -> FB2 m ()
+parseBinaryElement e =
+  case (findAttr (QName "id" Nothing Nothing) e, findAttr (QName "content-type" Nothing Nothing) e) of
+    (Nothing, _) -> throwError $ PandocParseError "<binary> element must have an \"id\" attribute"
+    (Just _, Nothing) -> throwError $ PandocParseError "<binary> element must have a \"content-type\" attribute"
+    (Just filename, contentType) -> insertMedia filename contentType (decodeLenient (pack (strContent e)))
+
+-- * Type parsers
+
+-- | Parse @authorType@
+parseAuthor :: PandocMonad m => Element -> FB2 m String
+parseAuthor e = unwords <$> mapM parseAuthorChild (elChildren e)
+
+parseAuthorChild :: PandocMonad m => Element -> FB2 m String
+parseAuthorChild e =
+  case qName $ elName e of
+    "first-name" -> pure $ strContent e
+    "middle-name" -> pure $ strContent e
+    "last-name" -> pure $ strContent e
+    "nickname" -> pure $ strContent e
+    "home-page" -> pure $ strContent e
+    "email" -> pure $ strContent e
+    name -> throwError $ PandocParseError ("Couldn't parse FB2 file: unexpected element " ++ name ++ " in author.")
+
+-- | Parse @titleType@
+parseTitle :: PandocMonad m => Element -> FB2 m Blocks
+parseTitle e = header <$> gets fb2SectionLevel <*> parseTitleType (elContent e)
+
+parseTitleType :: PandocMonad m => [Content] -> FB2 m Inlines
+parseTitleType c = mconcat . intersperse linebreak . catMaybes <$> mapM parseTitleContent c
+
+parseTitleContent :: PandocMonad m => Content -> FB2 m (Maybe Inlines)
+parseTitleContent (Elem e) =
+  case qName $ elName e of
+    "p" -> Just <$> parsePType e
+    "empty-line" -> pure $ Just mempty
+    _ -> pure mempty
+parseTitleContent _ = pure Nothing
+
+-- | Parse @imageType@
+parseImageElement :: PandocMonad m => Element -> FB2 m Blocks
+parseImageElement e =
+  case href of
+    Just src -> pure $ para $ imageWith (imgId, [], []) (removeHash src) title alt
+    Nothing -> throwError $ PandocParseError "Couldn't parse FB2 file: image without href."
+  where alt = maybe mempty str $ findAttr (QName "alt" Nothing Nothing) e
+        title = fromMaybe "" $ findAttr (QName "title" Nothing Nothing) e
+        imgId = fromMaybe "" $ findAttr (QName "id" Nothing Nothing) e
+        href = findAttr (QName "href" (Just "http://www.w3.org/1999/xlink") Nothing) e
+
+-- | Parse @pType@
+parsePType :: PandocMonad m => Element -> FB2 m Inlines
+parsePType = parseStyleType -- TODO add support for optional "id" and "style" attributes
+
+-- | Parse @citeType@
+parseCite :: PandocMonad m => Element -> FB2 m Blocks
+parseCite e = blockQuote . mconcat <$> mapM parseCiteChild (elChildren e)
+
+-- | Parse @citeType@ child
+parseCiteChild :: PandocMonad m => Element -> FB2 m Blocks
+parseCiteChild e =
+  case qName $ elName e of
+    "p" -> para <$> parsePType e
+    "poem" -> parsePoem e
+    "empty-line" -> pure horizontalRule
+    "subtitle" -> parseSubtitle e
+    "table" -> parseTable e
+    "text-author" -> para <$> parsePType e
+    name -> throwError $ PandocParseError ("Couldn't parse FB2 file: unexpected element " ++ name ++ " in cite.")
+
+-- | Parse @poemType@
+parsePoem :: PandocMonad m => Element -> FB2 m Blocks
+parsePoem e = mconcat <$> mapM parsePoemChild (elChildren e)
+
+parsePoemChild :: PandocMonad m => Element -> FB2 m Blocks
+parsePoemChild e =
+  case qName $ elName e of
+    "title" -> parseTitle e
+    "subtitle" -> parseSubtitle e
+    "epigraph" -> parseEpigraph e
+    "stanza" -> parseStanza e
+    "text-author" -> para <$> parsePType e
+    "date" -> pure $ para $ text $ strContent e
+    name -> throwError $ PandocParseError ("Couldn't parse FB2 file: unexpected element " ++ name ++ " in poem.")
+
+parseStanza :: PandocMonad m => Element -> FB2 m Blocks
+parseStanza e = fromList . joinLineBlocks . toList . mconcat <$> mapM parseStanzaChild (elChildren e)
+
+joinLineBlocks :: [Block] -> [Block]
+joinLineBlocks (LineBlock xs:LineBlock ys:zs) = joinLineBlocks (LineBlock (xs ++ ys) : zs)
+joinLineBlocks (x:xs) = x:joinLineBlocks xs
+joinLineBlocks [] = []
+
+parseStanzaChild :: PandocMonad m => Element -> FB2 m Blocks
+parseStanzaChild e =
+  case qName $ elName e of
+    "title" -> parseTitle e
+    "subtitle" -> parseSubtitle e
+    "v" -> lineBlock . (:[]) <$> parsePType e
+    name -> throwError $ PandocParseError ("Couldn't parse FB2 file: unexpected element " ++ name ++ " in stanza.")
+
+-- | Parse @epigraphType@
+parseEpigraph :: PandocMonad m => Element -> FB2 m Blocks
+parseEpigraph e =
+  divWith (divId, ["epigraph"], []) . mconcat <$> mapM parseEpigraphChild (elChildren e)
+  where divId = fromMaybe "" $ findAttr (QName "id" Nothing Nothing) e
+
+parseEpigraphChild :: PandocMonad m => Element -> FB2 m Blocks
+parseEpigraphChild e =
+  case qName $ elName e of
+    "p" -> para <$> parsePType e
+    "poem" -> parsePoem e
+    "cite" -> parseCite e
+    "empty-line" -> pure horizontalRule
+    "text-author" -> para <$> parsePType e
+    name -> throwError $ PandocParseError ("Couldn't parse FB2 file: unexpected element " ++ name ++ " in epigraph.")
+
+-- | Parse @annotationType@
+parseAnnotation :: PandocMonad m => Element -> FB2 m Blocks
+parseAnnotation e = mconcat <$> mapM parseAnnotationChild (elChildren e)
+
+parseAnnotationChild :: PandocMonad m => Element -> FB2 m Blocks
+parseAnnotationChild e =
+  case qName $ elName e of
+    "p" -> para <$> parsePType e
+    "poem" -> parsePoem e
+    "cite" -> parseCite e
+    "subtitle" -> parseSubtitle e
+    "table" -> parseTable e
+    "empty-line" -> pure horizontalRule
+    name -> throwError $ PandocParseError ("Couldn't parse FB2 file: unexpected element " ++ name ++ " in annotation.")
+
+-- | Parse @sectionType@
+parseSection :: PandocMonad m => Element -> FB2 m Blocks
+parseSection e = do
+  n <- gets fb2SectionLevel
+  modify $ \st -> st{ fb2SectionLevel = n + 1 }
+  let sectionId = fromMaybe "" $ findAttr (QName "id" Nothing Nothing) e
+  bs <- divWith (sectionId, ["section"], []) . mconcat <$> mapM parseSectionChild (elChildren e)
+  modify $ \st -> st{ fb2SectionLevel = n }
+  pure bs
+
+parseSectionChild :: PandocMonad m => Element -> FB2 m Blocks
+parseSectionChild e =
+  case qName $ elName e of
+    "title" -> parseBodyChild e
+    "epigraph" -> parseEpigraph e
+    "image" -> parseImageElement e
+    "annotation" -> parseAnnotation e
+    "poem" -> parsePoem e
+    "cite" -> parseCite e
+    "empty-line" -> pure horizontalRule
+    "table" -> parseTable e
+    "subtitle" -> parseSubtitle e
+    "p" -> para <$> parsePType e
+    "section" -> parseSection e
+    name -> throwError $ PandocParseError ("Couldn't parse FB2 file: unexpected element " ++ name ++ " in section.")
+
+-- | parse @styleType@
+parseStyleType :: PandocMonad m => Element -> FB2 m Inlines
+parseStyleType e = mconcat <$> mapM parseInline (elContent e)
+
+-- | Parse @namedStyleType@
+parseNamedStyle :: PandocMonad m => Element -> FB2 m Inlines
+parseNamedStyle e = do
+  content <- mconcat <$> mapM parseNamedStyleChild (elContent e)
+  let lang = maybeToList $ ("lang",) <$> findAttr (QName "lang" Nothing (Just "xml")) e
+  case findAttr (QName "name" Nothing Nothing) e of
+    Just name -> pure $ spanWith ("", [name], lang) content
+    Nothing -> throwError $ PandocParseError "Couldn't parse FB2 file: link without required name."
+
+parseNamedStyleChild :: PandocMonad m => Content -> FB2 m Inlines
+parseNamedStyleChild (Elem e) =
+  case qName (elName e) of
+    "strong" -> strong <$> parseStyleType e
+    "emphasis" -> emph <$> parseStyleType e
+    "style" -> parseNamedStyle e
+    "a" -> parseLinkType e
+    "strikethrough" -> strikeout <$> parseStyleType e
+    "sub" -> subscript <$> parseStyleType e
+    "sup" -> superscript <$> parseStyleType e
+    "code" -> pure $ code $ strContent e
+    "image" -> parseInlineImageElement e
+    name -> throwError $ PandocParseError ("Couldn't parse FB2 file: unexpected element " ++ name ++ ".")
+parseNamedStyleChild x = parseInline x
+
+-- | Parse @linkType@
+parseLinkType :: PandocMonad m => Element -> FB2 m Inlines
+parseLinkType e = do
+  content <- mconcat <$> mapM parseStyleLinkType (elContent e)
+  case findAttr (QName "href" (Just "http://www.w3.org/1999/xlink") Nothing) e of
+    Just href -> pure $ link href "" content
+    Nothing -> throwError $ PandocParseError "Couldn't parse FB2 file: link without required href."
+
+-- | Parse @styleLinkType@
+parseStyleLinkType :: PandocMonad m => Content -> FB2 m Inlines
+parseStyleLinkType x@(Elem e) =
+  case qName (elName e) of
+    "a" -> throwError $ PandocParseError "Couldn't parse FB2 file: links cannot be nested."
+    _ -> parseInline x
+parseStyleLinkType x = parseInline x
+
+-- | Parse @tableType@
+parseTable :: PandocMonad m => Element -> FB2 m Blocks
+parseTable _ = pure mempty -- TODO: tables are not supported yet
+
+-- | Parse @title-infoType@
+parseTitleInfoChild :: PandocMonad m => Element -> FB2 m ()
+parseTitleInfoChild e =
+  case qName (elName e) of
+    "genre" -> pure ()
+    "author" -> parseAuthor e >>= \author -> modify (\st -> st {fb2Authors = author:fb2Authors st})
+    "book-title" -> modify (setMeta "title" (text $ strContent e))
+    "annotation" -> parseAnnotation e >>= modify . setMeta "abstract"
+    "keywords" -> modify (setMeta "keywords" (map (MetaString . trim) $ splitOn "," $ strContent e))
+    "date" -> modify (setMeta "date" (text $ strContent e))
+    "coverpage" -> parseCoverPage e
+    "lang" -> pure ()
+    "src-lang" -> pure ()
+    "translator" -> pure ()
+    "sequence" -> pure ()
+    name -> throwError $ PandocParseError ("Couldn't parse FB2 file: unexpected element " ++ name ++ " in title-info.")
+
+parseCoverPage :: PandocMonad m => Element -> FB2 m ()
+parseCoverPage e =
+  case findChild (QName "image" (Just "http://www.gribuser.ru/xml/fictionbook/2.0") Nothing) e of
+    Just img -> case href of
+                  Just src -> modify (setMeta "cover-image" (MetaString $ removeHash src))
+                  Nothing -> pure ()
+                where href = findAttr (QName "href" (Just "http://www.w3.org/1999/xlink") Nothing) img
+    Nothing -> pure ()
+
+-- | Parse @inlineImageType@ element
+parseInlineImageElement :: PandocMonad m
+                        => Element
+                        -> FB2 m Inlines
+parseInlineImageElement e =
+  case href of
+    Just src -> pure $ imageWith ("", [], []) (removeHash src) "" alt
+    Nothing -> throwError $ PandocParseError "Couldn't parse FB2 file: inline image without href."
+  where alt = maybe mempty str $ findAttr (QName "alt" Nothing Nothing) e
+        href = findAttr (QName "href" (Just "http://www.w3.org/1999/xlink") Nothing) e
diff --git a/src/Text/Pandoc/Readers/HTML.hs b/src/Text/Pandoc/Readers/HTML.hs
--- a/src/Text/Pandoc/Readers/HTML.hs
+++ b/src/Text/Pandoc/Readers/HTML.hs
@@ -510,14 +510,16 @@
                              [Plain _] -> True
                              _         -> False
   let isSimple = all isSinglePlain $ concat (head':rows''')
-  let cols = length $ if null head' then head rows''' else head'
+  let cols = if null head'
+                then maximum (map length rows''')
+                else length head'
   -- add empty cells to short rows
   let addEmpties r = case cols - length r of
                            n | n > 0 -> r <> replicate n mempty
                              | otherwise -> r
   let rows = map addEmpties rows'''
   let aligns = case rows'' of
-                    (cs:_) -> map fst cs
+                    (cs:_) -> take cols $ map fst cs ++ repeat AlignDefault
                     _      -> replicate cols AlignDefault
   let widths = if null widths'
                   then if isSimple
diff --git a/src/Text/Pandoc/Readers/JATS.hs b/src/Text/Pandoc/Readers/JATS.hs
--- a/src/Text/Pandoc/Readers/JATS.hs
+++ b/src/Text/Pandoc/Readers/JATS.hs
@@ -1,5 +1,35 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-# LANGUAGE ExplicitForAll, TupleSections #-}
+{-# LANGUAGE TupleSections #-}
+{-
+Copyright (C) 2017-2018 Hamish Mackenzie
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+-}
+
+{- |
+   Module      : Text.Pandoc.Readers.JATS
+   Copyright   : Copyright (C) 2017-2018 Hamish Mackenzie
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of JATS XML to 'Pandoc' document.
+-}
+
 module Text.Pandoc.Readers.JATS ( readJATS ) where
 import Prelude
 import Control.Monad.State.Strict
diff --git a/src/Text/Pandoc/Readers/LaTeX.hs b/src/Text/Pandoc/Readers/LaTeX.hs
--- a/src/Text/Pandoc/Readers/LaTeX.hs
+++ b/src/Text/Pandoc/Readers/LaTeX.hs
@@ -48,7 +48,7 @@
 import Control.Monad
 import Control.Monad.Except (throwError)
 import Control.Monad.Trans (lift)
-import Data.Char (chr, isAlphaNum, isDigit, isLetter, ord, toLower)
+import Data.Char (chr, isAlphaNum, isDigit, isLetter, ord, toLower, toUpper)
 import Data.Default
 import Data.List (intercalate, isPrefixOf)
 import qualified Data.Map as M
@@ -164,6 +164,7 @@
                             , sInTableCell   :: Bool
                             , sLastHeaderNum :: HeaderNum
                             , sLabels        :: M.Map String [Inline]
+                            , sHasChapters   :: Bool
                             , sToggles       :: M.Map String Bool
                             }
      deriving Show
@@ -183,6 +184,7 @@
                               , sInTableCell   = False
                               , sLastHeaderNum = HeaderNum []
                               , sLabels        = M.empty
+                              , sHasChapters   = False
                               , sToggles       = M.empty
                               }
 
@@ -240,21 +242,30 @@
   return result
 
 rawLaTeXParser :: (PandocMonad m, HasMacros s, HasReaderOptions s)
-               => LP m a -> ParserT String s m (a, String)
-rawLaTeXParser parser = do
+               => LP m a -> LP m a -> ParserT String s m (a, String)
+rawLaTeXParser parser valParser = do
   inp <- getInput
   let toks = tokenize "source" $ T.pack inp
   pstate <- getState
-  let lstate = def{ sOptions = extractReaderOptions pstate
-                  , sMacros = extractMacros pstate }
-  let rawparser = (,) <$> withRaw parser <*> getState
-  res <- lift $ runParserT rawparser lstate "chunk" toks
-  case res of
+  let lstate = def{ sOptions = extractReaderOptions pstate }
+  let lstate' = lstate { sMacros = extractMacros pstate }
+  let rawparser = (,) <$> withRaw valParser <*> getState
+  res' <- lift $ runParserT (snd <$> withRaw parser) lstate "chunk" toks
+  case res' of
        Left _    -> mzero
-       Right ((val, raw), st) -> do
-         updateState (updateMacros (sMacros st <>))
-         rawstring <- takeP (T.length (untokenize raw))
-         return (val, rawstring)
+       Right toks' -> do
+         res <- lift $ runParserT (do doMacros 0
+                                      -- retokenize, applying macros
+                                      ts <- many (satisfyTok (const True))
+                                      setInput ts
+                                      rawparser)
+                        lstate' "chunk" toks'
+         case res of
+              Left _    -> mzero
+              Right ((val, raw), st) -> do
+                updateState (updateMacros (sMacros st <>))
+                _ <- takeP (T.length (untokenize toks'))
+                return (val, T.unpack (untokenize raw))
 
 applyMacros :: (PandocMonad m, HasMacros s, HasReaderOptions s)
             => String -> ParserT String s m String
@@ -275,19 +286,18 @@
   lookAhead (try (char '\\' >> letter))
   -- we don't want to apply newly defined latex macros to their own
   -- definitions:
-  snd <$> rawLaTeXParser macroDef
-  <|> ((snd <$> rawLaTeXParser (environment <|> blockCommand)) >>= applyMacros)
+  snd <$> rawLaTeXParser (environment <|> macroDef <|> blockCommand) blocks
 
 rawLaTeXInline :: (PandocMonad m, HasMacros s, HasReaderOptions s)
                => ParserT String s m String
 rawLaTeXInline = do
   lookAhead (try (char '\\' >> letter))
-  rawLaTeXParser (inlineEnvironment <|> inlineCommand') >>= applyMacros . snd
+  snd <$> rawLaTeXParser (inlineEnvironment <|> inlineCommand') inlines
 
 inlineCommand :: PandocMonad m => ParserT String ParserState m Inlines
 inlineCommand = do
   lookAhead (try (char '\\' >> letter))
-  fst <$> rawLaTeXParser (inlineEnvironment <|> inlineCommand')
+  fst <$> rawLaTeXParser (inlineEnvironment <|> inlineCommand') inlines
 
 tokenize :: SourceName -> Text -> [Tok]
 tokenize sourcename = totoks (initialPos sourcename)
@@ -1313,6 +1323,12 @@
   , ("slshape", extractSpaces emph <$> inlines)
   , ("scshape", extractSpaces smallcaps <$> inlines)
   , ("bfseries", extractSpaces strong <$> inlines)
+  , ("MakeUppercase", makeUppercase <$> tok)
+  , ("MakeTextUppercase", makeUppercase <$> tok) -- textcase
+  , ("uppercase", makeUppercase <$> tok)
+  , ("MakeLowercase", makeLowercase <$> tok)
+  , ("MakeTextLowercase", makeLowercase <$> tok)
+  , ("lowercase", makeLowercase <$> tok)
   , ("/", pure mempty) -- italic correction
   , ("aa", lit "å")
   , ("AA", lit "Å")
@@ -1513,6 +1529,16 @@
   , ("foreignlanguage", foreignlanguage)
   ]
 
+makeUppercase :: Inlines -> Inlines
+makeUppercase = fromList . walk (alterStr (map toUpper)) . toList
+
+makeLowercase :: Inlines -> Inlines
+makeLowercase = fromList . walk (alterStr (map toLower)) . toList
+
+alterStr :: (String -> String) -> Inline -> Inline
+alterStr f (Str xs) = Str (f xs)
+alterStr _ x = x
+
 foreignlanguage :: PandocMonad m => LP m Inlines
 foreignlanguage = do
   babelLang <- T.unpack . untokenize <$> braced
@@ -1685,6 +1711,9 @@
    , "clearpage"
    , "pagebreak"
    , "titleformat"
+   , "listoffigures"
+   , "listoftables"
+   , "write"
    ]
 
 isInlineCommand :: Text -> Bool
@@ -1984,9 +2013,13 @@
           try (spaces >> controlSeq "label"
                >> spaces >> toksToString <$> braced)
   let classes' = if starred then "unnumbered" : classes else classes
+  when (lvl == 0) $
+    updateState $ \st -> st{ sHasChapters = True }
   unless starred $ do
     hn <- sLastHeaderNum <$> getState
-    let num = incrementHeaderNum lvl hn
+    hasChapters <- sHasChapters <$> getState
+    let lvl' = lvl + if hasChapters then 1 else 0
+    let num = incrementHeaderNum lvl' hn
     updateState $ \st -> st{ sLastHeaderNum = num }
     updateState $ \st -> st{ sLabels = M.insert lab
                             [Str (renderHeaderNum num)]
@@ -2111,6 +2144,7 @@
 environments = M.fromList
    [ ("document", env "document" blocks)
    , ("abstract", mempty <$ (env "abstract" blocks >>= addMeta "abstract"))
+   , ("sloppypar", env "sloppypar" $ blocks)
    , ("letter", env "letter" letterContents)
    , ("minipage", env "minipage" $
           skipopts *> spaces *> optional braced *> spaces *> blocks)
@@ -2142,19 +2176,6 @@
                        codeBlockWith attr <$> verbEnv "lstlisting")
    , ("minted", minted)
    , ("obeylines", obeylines)
-   , ("displaymath", mathEnvWith para Nothing "displaymath")
-   , ("equation", mathEnvWith para Nothing "equation")
-   , ("equation*", mathEnvWith para Nothing "equation*")
-   , ("gather", mathEnvWith para (Just "gathered") "gather")
-   , ("gather*", mathEnvWith para (Just "gathered") "gather*")
-   , ("multline", mathEnvWith para (Just "gathered") "multline")
-   , ("multline*", mathEnvWith para (Just "gathered") "multline*")
-   , ("eqnarray", mathEnvWith para (Just "aligned") "eqnarray")
-   , ("eqnarray*", mathEnvWith para (Just "aligned") "eqnarray*")
-   , ("align", mathEnvWith para (Just "aligned") "align")
-   , ("align*", mathEnvWith para (Just "aligned") "align*")
-   , ("alignat", mathEnvWith para (Just "aligned") "alignat")
-   , ("alignat*", mathEnvWith para (Just "aligned") "alignat*")
    , ("tikzpicture", rawVerbEnv "tikzpicture")
    -- etoolbox
    , ("ifstrequal", ifstrequal)
@@ -2165,11 +2186,14 @@
    ]
 
 environment :: PandocMonad m => LP m Blocks
-environment = do
+environment = try $ do
   controlSeq "begin"
   name <- untokenize <$> braced
-  M.findWithDefault mzero name environments
-    <|> rawEnv name
+  M.findWithDefault mzero name environments <|>
+    if M.member name (inlineEnvironments
+                       :: M.Map Text (LP PandocPure Inlines))
+       then mzero
+       else rawEnv name
 
 env :: PandocMonad m => Text -> LP m a -> LP m a
 env name p = p <* end_ name
diff --git a/src/Text/Pandoc/Readers/Markdown.hs b/src/Text/Pandoc/Readers/Markdown.hs
--- a/src/Text/Pandoc/Readers/Markdown.hs
+++ b/src/Text/Pandoc/Readers/Markdown.hs
@@ -674,6 +674,8 @@
   char '='
   val <- enclosed (char '"') (char '"') litChar
      <|> enclosed (char '\'') (char '\'') litChar
+     <|> ("" <$ try (string "\"\""))
+     <|> ("" <$ try (string "''"))
      <|> many (escapedChar' <|> noneOf " \t\n\r}")
   return $ \(id',cs,kvs) ->
     case key of
@@ -910,6 +912,17 @@
   blanks <- many blankline
   return $ concat (x:xs) ++ blanks
 
+-- Variant of blanklines that doesn't require blank lines
+-- before a fence or eof.
+blanklines' :: PandocMonad m => MarkdownParser m [Char]
+blanklines' = blanklines <|> try checkDivCloser
+  where checkDivCloser = do
+          guardEnabled Ext_fenced_divs
+          divLevel <- stateFencedDivLevel <$> getState
+          guard (divLevel >= 1)
+          lookAhead divFenceEnd
+          return ""
+
 notFollowedByDivCloser :: PandocMonad m => MarkdownParser m ()
 notFollowedByDivCloser =
   guardDisabled Ext_fenced_divs <|>
@@ -1251,7 +1264,7 @@
 
 -- Parse a table footer - dashed lines followed by blank line.
 tableFooter :: PandocMonad m => MarkdownParser m String
-tableFooter = try $ skipNonindentSpaces >> many1 (dashedLine '-') >> blanklines
+tableFooter = try $ skipNonindentSpaces >> many1 (dashedLine '-') >> blanklines'
 
 -- Parse a table separator - dashed line.
 tableSep :: PandocMonad m => MarkdownParser m Char
@@ -1262,7 +1275,7 @@
              => [Int]
              -> MarkdownParser m [String]
 rawTableLine indices = do
-  notFollowedBy' (blanklines <|> tableFooter)
+  notFollowedBy' (blanklines' <|> tableFooter)
   line <- many1Till anyChar newline
   return $ map trim $ tail $
            splitStringByIndices (init indices) line
@@ -1300,7 +1313,7 @@
   (aligns, _widths, heads', lines') <-
        tableWith (simpleTableHeader headless) tableLine
               (return ())
-              (if headless then tableFooter else tableFooter <|> blanklines)
+              (if headless then tableFooter else tableFooter <|> blanklines')
   -- Simple tables get 0s for relative column widths (i.e., use default)
   return (aligns, replicate (length aligns) 0, heads', lines')
 
@@ -1328,11 +1341,16 @@
   newline
   let (lengths, lines') = unzip dashes
   let indices  = scanl (+) (length initSp) lines'
+  -- compensate for the fact that intercolumn spaces are
+  -- not included in the last index:
+  let indices' = case reverse indices of
+                      []     -> []
+                      (x:xs) -> reverse (x+1:xs)
   rawHeadsList <- if headless
                      then fmap (map (:[]) . tail .
-                              splitStringByIndices (init indices)) $ lookAhead anyLine
+                              splitStringByIndices (init indices')) $ lookAhead anyLine
                      else return $ transpose $ map
-                           (tail . splitStringByIndices (init indices))
+                           (tail . splitStringByIndices (init indices'))
                            rawContent
   let aligns   = zipWith alignType rawHeadsList lengths
   let rawHeads = if headless
@@ -1340,7 +1358,7 @@
                     else map (unlines . map trim) rawHeadsList
   heads <- fmap sequence $
             mapM ((parseFromString' (mconcat <$> many plain)).trim) rawHeads
-  return (heads, aligns, indices)
+  return (heads, aligns, indices')
 
 -- Parse a grid table:  starts with row of '-' on top, then header
 -- (which may be grid), then the rows,
@@ -2146,7 +2164,6 @@
 doubleQuoted :: PandocMonad m => MarkdownParser m (F Inlines)
 doubleQuoted = try $ do
   doubleQuoteStart
-  contents <- mconcat <$> many (try $ notFollowedBy doubleQuoteEnd >> inline)
-  withQuoteContext InDoubleQuote (doubleQuoteEnd >> return
-       (fmap B.doubleQuoted . trimInlinesF $ contents))
-   <|> return (return (B.str "\8220") <> contents)
+  withQuoteContext InDoubleQuote $
+    fmap B.doubleQuoted . trimInlinesF . mconcat <$>
+      many1Till inline doubleQuoteEnd
diff --git a/src/Text/Pandoc/Readers/MediaWiki.hs b/src/Text/Pandoc/Readers/MediaWiki.hs
--- a/src/Text/Pandoc/Readers/MediaWiki.hs
+++ b/src/Text/Pandoc/Readers/MediaWiki.hs
@@ -1,7 +1,5 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-# LANGUAGE FlexibleInstances    #-}
-{-# LANGUAGE RelaxedPolyRec       #-}
-{-# LANGUAGE TypeSynonymInstances #-}
+{-# LANGUAGE RelaxedPolyRec #-}
 -- RelaxedPolyRec needed for inlinesBetween on GHC < 7
 {-
   Copyright (C) 2012-2018 John MacFarlane <jgm@berkeley.edu>
@@ -232,7 +230,8 @@
 table :: PandocMonad m => MWParser m Blocks
 table = do
   tableStart
-  styles <- option [] parseAttrs
+  styles <- option [] $
+               parseAttrs <* skipMany spaceChar <* optional (char '|')
   skipMany spaceChar
   optional blanklines
   let tableWidth = case lookup "width" styles of
@@ -283,17 +282,29 @@
 
 cellsep :: PandocMonad m => MWParser m ()
 cellsep = try $ do
+  col <- sourceColumn <$> getPosition
   skipSpaces
-  (char '|' *> notFollowedBy (oneOf "-}+") *> optional (char '|'))
-    <|> (char '!' *> optional (char '!'))
+  let pipeSep = do
+        char '|'
+        notFollowedBy (oneOf "-}+")
+        if col == 1
+           then optional (char '|')
+           else void (char '|')
+  let exclSep = do
+        char '!'
+        if col == 1
+           then optional (char '!')
+           else void (char '!')
+  pipeSep <|> exclSep
 
 tableCaption :: PandocMonad m => MWParser m Inlines
 tableCaption = try $ do
   guardColumnOne
   skipSpaces
   sym "|+"
-  optional (try $ parseAttr *> skipSpaces *> char '|' *> skipSpaces)
-  (trimInlines . mconcat) <$> many (notFollowedBy (cellsep <|> rowsep) *> inline)
+  optional (try $ parseAttr *> skipSpaces *> char '|' *> blanklines)
+  (trimInlines . mconcat) <$>
+    many (notFollowedBy (cellsep <|> rowsep) *> inline)
 
 tableRow :: PandocMonad m => MWParser m [((Alignment, Double), Blocks)]
 tableRow = try $ skipMany htmlComment *> many tableCell
diff --git a/src/Text/Pandoc/Readers/Muse.hs b/src/Text/Pandoc/Readers/Muse.hs
--- a/src/Text/Pandoc/Readers/Muse.hs
+++ b/src/Text/Pandoc/Readers/Muse.hs
@@ -1,5 +1,6 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-# LANGUAGE FlexibleContexts      #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE TupleSections #-}
 {-
   Copyright (C) 2017-2018 Alexander Krotov <ilabdsf@gmail.com>
 
@@ -35,14 +36,14 @@
 - Org tables
 - table.el tables
 - Images with attributes (floating and width)
-- Citations and <biblio>
-- <play> environment
+- <cite> tag
 -}
 module Text.Pandoc.Readers.Muse (readMuse) where
 
 import Prelude
 import Control.Monad
 import Control.Monad.Except (throwError)
+import Data.Bifunctor
 import Data.Char (isLetter)
 import Data.Default
 import Data.List (stripPrefix, intercalate)
@@ -83,24 +84,21 @@
                            , museLastStrPos :: Maybe SourcePos -- ^ Position after last str parsed
                            , museLogMessages :: [LogMessage]
                            , museNotes :: M.Map String (SourcePos, F Blocks)
-                           , museInLink :: Bool
-                           , museInPara :: Bool
+                           , museInLink :: Bool -- ^ True when parsing a link description to avoid nested links
+                           , museInPara :: Bool -- ^ True when looking for a paragraph terminator
                            }
 
 instance Default MuseState where
-  def = defaultMuseState
-
-defaultMuseState :: MuseState
-defaultMuseState = MuseState { museMeta = return nullMeta
-                             , museOptions = def
-                             , museHeaders = M.empty
-                             , museIdentifierList = Set.empty
-                             , museLastStrPos = Nothing
-                             , museLogMessages = []
-                             , museNotes = M.empty
-                             , museInLink = False
-                             , museInPara = False
-                             }
+  def = MuseState { museMeta = return nullMeta
+                  , museOptions = def
+                  , museHeaders = M.empty
+                  , museIdentifierList = Set.empty
+                  , museLastStrPos = Nothing
+                  , museLogMessages = []
+                  , museNotes = M.empty
+                  , museInLink = False
+                  , museInPara = False
+                  }
 
 type MuseParser = ParserT String MuseState
 
@@ -123,10 +121,7 @@
   addLogMessage m s = s{ museLogMessages = m : museLogMessages s }
   getLogMessages = reverse . museLogMessages
 
---
--- main parser
---
-
+-- | Parse Muse document
 parseMuse :: PandocMonad m => MuseParser m Pandoc
 parseMuse = do
   many directive
@@ -138,14 +133,56 @@
   reportLogMessages
   return doc
 
---
--- utility functions
---
+-- * Utility functions
 
+commonPrefix :: String -> String -> String
+commonPrefix _ [] = []
+commonPrefix [] _ = []
+commonPrefix (x:xs) (y:ys)
+  | x == y    = x : commonPrefix xs ys
+  | otherwise = []
+
+-- | Trim up to one newline from the beginning of the string.
+lchop :: String -> String
+lchop s = case s of
+                    '\n':ss -> ss
+                    _       -> s
+
+-- | Trim up to one newline from the end of the string.
+rchop :: String -> String
+rchop = reverse . lchop . reverse
+
+dropSpacePrefix :: [String] -> [String]
+dropSpacePrefix lns =
+  map (drop maxIndent) lns
+  where flns = filter (not . all (== ' ')) lns
+        maxIndent = if null flns then maximum (map length lns) else length $ takeWhile (== ' ') $ foldl1 commonPrefix flns
+
+atStart :: PandocMonad m => MuseParser m a -> MuseParser m a
+atStart p = do
+  pos <- getPosition
+  st <- getState
+  guard $ museLastStrPos st /= Just pos
+  p
+
+-- * Parsers
+
+-- | Parse end-of-line, which can be either a newline or end-of-file.
 eol :: Stream s m Char => ParserT s st m ()
 eol = void newline <|> eof
 
-htmlElement :: PandocMonad m => String -> MuseParser m (Attr, String)
+someUntil :: (Stream s m t)
+          => ParserT s u m a
+          -> ParserT s u m b
+          -> ParserT s u m ([a], b)
+someUntil p end = first <$> ((:) <$> p) <*> manyUntil p end
+
+-- ** HTML parsers
+
+-- | Parse HTML tag, returning its attributes and literal contents.
+htmlElement :: PandocMonad m
+            => String -- ^ Tag name
+            -> MuseParser m (Attr, String)
 htmlElement tag = try $ do
   (TagOpen _ attr, _) <- htmlTag (~== TagOpen tag [])
   content <- manyTill anyChar endtag
@@ -153,13 +190,16 @@
   where
     endtag = void $ htmlTag (~== TagClose tag)
 
-htmlBlock :: PandocMonad m => String -> MuseParser m (Attr, String)
+htmlBlock :: PandocMonad m
+          => String -- ^ Tag name
+          -> MuseParser m (Attr, String)
 htmlBlock tag = try $ do
   many spaceChar
   res <- htmlElement tag
   manyTill spaceChar eol
   return res
 
+-- | Convert HTML attributes to Pandoc 'Attr'
 htmlAttrToPandoc :: [Attribute String] -> Attr
 htmlAttrToPandoc attrs = (ident, classes, keyvals)
   where
@@ -168,50 +208,24 @@
     keyvals = [(k,v) | (k,v) <- attrs, k /= "id" && k /= "class"]
 
 parseHtmlContent :: PandocMonad m
-                 => String -> MuseParser m (Attr, F Blocks)
+                 => String -- ^ Tag name
+                 -> MuseParser m (Attr, F Blocks)
 parseHtmlContent tag = try $ do
   many spaceChar
   pos <- getPosition
   (TagOpen _ attr, _) <- htmlTag (~== TagOpen tag [])
   manyTill spaceChar eol
-  content <- parseBlocksTill (try $ ((count (sourceColumn pos - 1) spaceChar) >> endtag))
+  content <- parseBlocksTill $ try $ count (sourceColumn pos - 1) spaceChar >> endtag
   manyTill spaceChar eol -- closing tag must be followed by optional whitespace and newline
   return (htmlAttrToPandoc attr, content)
   where
     endtag = void $ htmlTag (~== TagClose tag)
 
-commonPrefix :: String -> String -> String
-commonPrefix _ [] = []
-commonPrefix [] _ = []
-commonPrefix (x:xs) (y:ys)
-  | x == y    = x : commonPrefix xs ys
-  | otherwise = []
-
-atStart :: PandocMonad m => MuseParser m a -> MuseParser m a
-atStart p = do
-  pos <- getPosition
-  st <- getState
-  guard $ museLastStrPos st /= Just pos
-  p
-
-someUntil :: (Stream s m t)
-          => ParserT s u m a
-          -> ParserT s u m b
-          -> ParserT s u m ([a], b)
-someUntil p end = do
-  first <- p
-  (rest, e) <- manyUntil p end
-  return (first:rest, e)
-
---
--- directive parsers
---
+-- ** Directive parsers
 
 -- While not documented, Emacs Muse allows "-" in directive name
 parseDirectiveKey :: PandocMonad m => MuseParser m String
-parseDirectiveKey = do
-  char '#'
-  many (letter <|> char '-')
+parseDirectiveKey = char '#' *> many (letter <|> char '-')
 
 parseEmacsDirective :: PandocMonad m => MuseParser m (String, F Inlines)
 parseEmacsDirective = do
@@ -238,9 +252,7 @@
   where translateKey "cover" = "cover-image"
         translateKey x = x
 
---
--- block parsers
---
+-- ** Block parsers
 
 parseBlocks :: PandocMonad m
             => MuseParser m (F Blocks)
@@ -251,18 +263,15 @@
        paraStart)
   where
     parseEnd = mempty <$ eof
-    blockStart = do first <- header <|> blockElements <|> emacsNoteBlock
-                    rest <- parseBlocks
-                    return $ first B.<> rest
+    blockStart = ((B.<>) <$> (emacsHeading <|> blockElements <|> emacsNoteBlock)
+                         <*> parseBlocks) <|> (uncurry (B.<>) <$> amuseHeadingUntil parseBlocks)
     listStart = do
       updateState (\st -> st { museInPara = False })
-      (first, rest) <- anyListUntil parseBlocks <|> amuseNoteBlockUntil parseBlocks
-      return $ first B.<> rest
+      uncurry (B.<>) <$> (anyListUntil parseBlocks <|> amuseNoteBlockUntil parseBlocks)
     paraStart = do
       indent <- length <$> many spaceChar
-      (first, rest) <- paraUntil parseBlocks
-      let first' = if indent >= 2 && indent < 6 then B.blockQuote <$> first else first
-      return $ first' B.<> rest
+      uncurry (B.<>) . first (p indent) <$> paraUntil parseBlocks
+      where p indent = if indent >= 2 && indent < 6 then fmap B.blockQuote else id
 
 parseBlocksTill :: PandocMonad m
                 => MuseParser m a
@@ -274,19 +283,11 @@
        paraStart)
   where
     parseEnd = mempty <$ end
-    blockStart = do first <- blockElements
-                    rest <- continuation
-                    return $ first B.<> rest
+    blockStart = (B.<>) <$> blockElements <*> continuation
     listStart = do
       updateState (\st -> st { museInPara = False })
-      (first, e) <- anyListUntil ((Left <$> end) <|> (Right <$> continuation))
-      case e of
-        Left _ -> return first
-        Right rest -> return $ first B.<> rest
-    paraStart = do (first, e) <- paraUntil ((Left <$> end) <|> (Right <$> continuation))
-                   case e of
-                     Left _ -> return first
-                     Right rest -> return $ first B.<> rest
+      uncurry (B.<>) <$> anyListUntil (parseEnd <|> continuation)
+    paraStart = uncurry (B.<>) <$> paraUntil (parseEnd <|> continuation)
     continuation = parseBlocksTill end
 
 listItemContentsUntil :: PandocMonad m
@@ -299,24 +300,17 @@
   try listStart <|>
   try paraStart
   where
-    parsePre = do e <- pre
-                  return (mempty, e)
-    parseEnd = do e <- end
-                  return (mempty, e)
+    parsePre = (mempty,) <$> pre
+    parseEnd = (mempty,) <$> end
     paraStart = do
-      (first, e) <- paraUntil ((Left <$> pre) <|> (Right <$> continuation) <|> (Left <$> end))
-      case e of
-        Left ee -> return (first, ee)
-        Right (rest, ee) -> return (first B.<> rest, ee)
-    blockStart = do first <- blockElements
-                    (rest, e) <- parsePre <|> continuation <|> parseEnd
-                    return (first B.<> rest, e)
+      (f, (r, e)) <- paraUntil (parsePre <|> continuation <|> parseEnd)
+      return (f B.<> r, e)
+    blockStart = first <$> ((B.<>) <$> blockElements)
+                       <*> (parsePre <|> continuation <|> parseEnd)
     listStart = do
       updateState (\st -> st { museInPara = False })
-      (first, e) <- anyListUntil ((Left <$> pre) <|> (Right <$> continuation) <|> (Left <$> end))
-      case e of
-        Left ee -> return (first, ee)
-        Right (rest, ee) -> return (first B.<> rest, ee)
+      (f, (r, e)) <- anyListUntil (parsePre <|> continuation <|> parseEnd)
+      return (f B.<> r, e)
     continuation = try $ do blank <- optionMaybe blankline
                             skipMany blankline
                             indentWith col
@@ -343,19 +337,24 @@
          , rightTag
          , quoteTag
          , divTag
+         , biblioTag
+         , playTag
          , verseTag
          , lineBlock
          , table
          , commentTag
          ]
 
+-- | Parse a line comment, starting with @;@ in the first column.
 comment :: PandocMonad m => MuseParser m (F Blocks)
 comment = try $ do
+  getPosition >>= \pos -> guard (sourceColumn pos == 1)
   char ';'
   optional (spaceChar >> many (noneOf "\n"))
   eol
   return mempty
 
+-- | Parse a horizontal rule, consisting of 4 or more @\'-\'@ characters.
 separator :: PandocMonad m => MuseParser m (F Blocks)
 separator = try $ do
   string "----"
@@ -364,17 +363,37 @@
   eol
   return $ return B.horizontalRule
 
-header :: PandocMonad m => MuseParser m (F Blocks)
-header = try $ do
+-- | Parse a single-line heading.
+emacsHeading :: PandocMonad m => MuseParser m (F Blocks)
+emacsHeading = try $ do
+  guardDisabled Ext_amuse
+  anchorId <- option "" $ try (parseAnchor <* manyTill spaceChar eol)
   getPosition >>= \pos -> guard (sourceColumn pos == 1)
   level <- fmap length $ many1 $ char '*'
   guard $ level <= 5
   spaceChar
   content <- trimInlinesF . mconcat <$> manyTill inline eol
-  anchorId <- option "" parseAnchor
   attr <- registerHeader (anchorId, [], []) (runF content def)
   return $ B.headerWith attr level <$> content
 
+-- | Parse a multi-line heading.
+-- It is a Text::Amuse extension, Emacs Muse does not allow heading to span multiple lines.
+amuseHeadingUntil :: PandocMonad m
+                  => MuseParser m a -- ^ Terminator parser
+                  -> MuseParser m (F Blocks, a)
+amuseHeadingUntil end = try $ do
+  guardEnabled Ext_amuse
+  anchorId <- option "" $ try (parseAnchor <* manyTill spaceChar eol)
+  getPosition >>= \pos -> guard (sourceColumn pos == 1)
+  level <- fmap length $ many1 $ char '*'
+  guard $ level <= 5
+  spaceChar
+  (content, e) <- paraContentsUntil end
+  attr <- registerHeader (anchorId, [], []) (runF content def)
+  return (B.headerWith attr level <$> content, e)
+
+-- | Parse an example between @{{{@ and @}}}@.
+-- It is an Amusewiki extension influenced by Creole wiki, as described in @Text::Amuse@ documentation.
 example :: PandocMonad m => MuseParser m (F Blocks)
 example = try $ do
   string "{{{"
@@ -382,52 +401,63 @@
   contents <- manyTill anyChar $ try (optional blankline >> string "}}}")
   return $ return $ B.codeBlock contents
 
--- Trim up to one newline from the beginning of the string.
-lchop :: String -> String
-lchop s = case s of
-                    '\n':ss -> ss
-                    _       -> s
-
--- Trim up to one newline from the end of the string.
-rchop :: String -> String
-rchop = reverse . lchop . reverse
-
-dropSpacePrefix :: [String] -> [String]
-dropSpacePrefix lns =
-  map (drop maxIndent) lns
-  where flns = filter (not . all (== ' ')) lns
-        maxIndent = if null flns then maximum (map length lns) else length $ takeWhile (== ' ') $ foldl1 commonPrefix flns
-
+-- | Parse an @\<example>@ tag.
 exampleTag :: PandocMonad m => MuseParser m (F Blocks)
 exampleTag = try $ do
   (attr, contents) <- htmlBlock "example"
   return $ return $ B.codeBlockWith attr $ rchop $ intercalate "\n" $ dropSpacePrefix $ splitOn "\n" $ lchop contents
 
+-- | Parse a @\<literal>@ tag as a raw block.
+-- For 'RawInline' @\<literal>@ parser, see 'inlineLiteralTag'.
 literalTag :: PandocMonad m => MuseParser m (F Blocks)
-literalTag =
-  (return . rawBlock) <$> htmlBlock "literal"
+literalTag = try $ do
+  many spaceChar
+  (TagOpen _ attr, _) <- htmlTag (~== TagOpen "literal" [])
+  manyTill spaceChar eol
+  content <- manyTill anyChar endtag
+  manyTill spaceChar eol
+  return $ return $ rawBlock (htmlAttrToPandoc attr, content)
   where
+    endtag = void $ htmlTag (~== TagClose "literal")
     -- FIXME: Emacs Muse inserts <literal> without style into all output formats, but we assume HTML
     format (_, _, kvs)        = fromMaybe "html" $ lookup "style" kvs
     rawBlock (attrs, content) = B.rawBlock (format attrs) $ rchop $ intercalate "\n" $ dropSpacePrefix $ splitOn "\n" $ lchop content
 
--- <center> tag is ignored
+-- | Parse @\<center>@ tag.
+-- Currently it is ignored as Pandoc cannot represent centered blocks.
 centerTag :: PandocMonad m => MuseParser m (F Blocks)
 centerTag = snd <$> parseHtmlContent "center"
 
--- <right> tag is ignored
+-- | Parse @\<right>@ tag.
+-- Currently it is ignored as Pandoc cannot represent centered blocks.
 rightTag :: PandocMonad m => MuseParser m (F Blocks)
 rightTag = snd <$> parseHtmlContent "right"
 
+-- | Parse @\<quote>@ tag.
 quoteTag :: PandocMonad m => MuseParser m (F Blocks)
 quoteTag = fmap B.blockQuote . snd <$> parseHtmlContent "quote"
 
--- <div> tag is supported by Emacs Muse, but not Amusewiki 2.025
+-- | Parse @\<div>@ tag.
+-- @\<div>@ tag is supported by Emacs Muse, but not Amusewiki 2.025.
 divTag :: PandocMonad m => MuseParser m (F Blocks)
 divTag = do
   (attrs, content) <- parseHtmlContent "div"
   return $ B.divWith attrs <$> content
 
+-- | Parse @\<biblio>@ tag, the result is the same as @\<div class="biblio">@.
+-- @\<biblio>@ tag is supported only in Text::Amuse mode.
+biblioTag :: PandocMonad m => MuseParser m (F Blocks)
+biblioTag = do
+  guardEnabled Ext_amuse
+  fmap (B.divWith ("", ["biblio"], [])) . snd <$> parseHtmlContent "biblio"
+
+-- | Parse @\<play>@ tag, the result is the same as @\<div class="play">@.
+-- @\<play>@ tag is supported only in Text::Amuse mode.
+playTag :: PandocMonad m => MuseParser m (F Blocks)
+playTag = do
+  guardEnabled Ext_amuse
+  fmap (B.divWith ("", ["play"], [])) . snd <$> parseHtmlContent "play"
+
 verseLine :: PandocMonad m => MuseParser m (F Inlines)
 verseLine = do
   indent <- (B.str <$> many1 (char ' ' >> pure '\160')) <|> pure mempty
@@ -439,32 +469,39 @@
   lns <- many verseLine
   return $ B.lineBlock <$> sequence lns
 
+-- | Parse @\<verse>@ tag.
 verseTag :: PandocMonad m => MuseParser m (F Blocks)
 verseTag = do
   (_, content) <- htmlBlock "verse"
   parseFromString verseLines (intercalate "\n" $ dropSpacePrefix $ splitOn "\n" $ lchop content)
 
+-- | Parse @\<comment>@ tag.
 commentTag :: PandocMonad m => MuseParser m (F Blocks)
 commentTag = htmlBlock "comment" >> return mempty
 
--- Indented paragraph is either center, right or quote
+-- | Parse paragraph contents.
+paraContentsUntil :: PandocMonad m
+                  => MuseParser m a -- ^ Terminator parser
+                  -> MuseParser m (F Inlines, a)
+paraContentsUntil end = do
+  updateState (\st -> st { museInPara = True })
+  (l, e) <- someUntil inline $ try (manyTill spaceChar eol >> end)
+  updateState (\st -> st { museInPara = False })
+  return (trimInlinesF $ mconcat l, e)
+
+-- | Parse a paragraph.
 paraUntil :: PandocMonad m
-          => MuseParser m a
+          => MuseParser m a -- ^ Terminator parser
           -> MuseParser m (F Blocks, a)
 paraUntil end = do
   state <- getState
   guard $ not $ museInPara state
-  setState $ state{ museInPara = True }
-  (l, e) <- someUntil inline $ try (manyTill spaceChar eol >> end)
-  updateState (\st -> st { museInPara = False })
-  return (fmap B.para $ trimInlinesF $ mconcat l, e)
+  first (fmap B.para) <$> paraContentsUntil end
 
 noteMarker :: PandocMonad m => MuseParser m String
 noteMarker = try $ do
   char '['
-  first <- oneOf "123456789"
-  rest <- manyTill digit (char ']')
-  return $ first:rest
+  (:) <$> oneOf "123456789" <*> manyTill digit (char ']')
 
 -- Amusewiki version of note
 -- Parsing is similar to list item, except that note marker is used instead of list marker
@@ -478,9 +515,8 @@
   updateState (\st -> st { museInPara = False })
   (content, e) <- listItemContentsUntil (sourceColumn pos - 1) (fail "x") end
   oldnotes <- museNotes <$> getState
-  case M.lookup ref oldnotes of
-    Just _  -> logMessage $ DuplicateNoteReference ref pos
-    Nothing -> return ()
+  when (M.member ref oldnotes)
+    (logMessage $ DuplicateNoteReference ref pos)
   updateState $ \s -> s{ museNotes = M.insert ref (pos, content) oldnotes }
   return (mempty, e)
 
@@ -493,9 +529,8 @@
   ref <- noteMarker <* skipSpaces
   content <- mconcat <$> blocksTillNote
   oldnotes <- museNotes <$> getState
-  case M.lookup ref oldnotes of
-    Just _  -> logMessage $ DuplicateNoteReference ref pos
-    Nothing -> return ()
+  when (M.member ref oldnotes)
+    (logMessage $ DuplicateNoteReference ref pos)
   updateState $ \s -> s{ museNotes = M.insert ref (pos, content) oldnotes }
   return mempty
   where
@@ -520,29 +555,28 @@
   blankline
   pure mempty
 
+-- | Parse a line block indicated by @\'>\'@ characters.
 lineBlock :: PandocMonad m => MuseParser m (F Blocks)
 lineBlock = try $ do
+  many spaceChar
   col <- sourceColumn <$> getPosition
   lns <- (blanklineVerseLine <|> lineVerseLine) `sepBy1'` try (indentWith (col - 1))
   return $ B.lineBlock <$> sequence lns
 
---
--- lists
---
+-- *** List parsers
 
 bulletListItemsUntil :: PandocMonad m
-                     => Int
-                     -> MuseParser m a
+                     => Int -- ^ Indentation
+                     -> MuseParser m a -- ^ Terminator parser
                      -> MuseParser m ([F Blocks], a)
 bulletListItemsUntil indent end = try $ do
   char '-'
   void spaceChar <|> lookAhead eol
   updateState (\st -> st { museInPara = False })
-  (x, e) <- listItemContentsUntil (indent + 2) (Right <$> try (optional blankline >> indentWith indent >> bulletListItemsUntil indent end)) (Left <$> end)
-  case e of
-    Left ee -> return ([x], ee)
-    Right (xs, ee) -> return (x:xs, ee)
+  (x, (xs, e)) <- listItemContentsUntil (indent + 2) (try (optional blankline >> indentWith indent >> bulletListItemsUntil indent end)) (([],) <$> end)
+  return (x:xs, e)
 
+-- | Parse a bullet list.
 bulletListUntil :: PandocMonad m
                 => MuseParser m a
                 -> MuseParser m (F Blocks, a)
@@ -564,16 +598,15 @@
 museOrderedListMarker :: PandocMonad m
                       => ListNumberStyle
                       -> MuseParser m Int
-museOrderedListMarker style = do
-  (_, start) <- case style of
-                  Decimal    -> decimal
-                  UpperRoman -> upperRoman
-                  LowerRoman -> lowerRoman
-                  UpperAlpha -> upperAlpha
-                  LowerAlpha -> lowerAlpha
-                  _          -> fail "Unhandled case"
-  char '.'
-  return start
+museOrderedListMarker style =
+  snd <$> p <* char '.'
+  where p = case style of
+              Decimal    -> decimal
+              UpperRoman -> upperRoman
+              LowerRoman -> lowerRoman
+              UpperAlpha -> upperAlpha
+              LowerAlpha -> lowerAlpha
+              _          -> fail "Unhandled case"
 
 orderedListItemsUntil :: PandocMonad m
                       => Int
@@ -587,11 +620,10 @@
       pos <- getPosition
       void spaceChar <|> lookAhead eol
       updateState (\st -> st { museInPara = False })
-      (x, e) <- listItemContentsUntil (sourceColumn pos) (Right <$> try (optionMaybe blankline >> indentWith indent >> museOrderedListMarker style >> continuation)) (Left <$> end)
-      case e of
-        Left ee -> return ([x], ee)
-        Right (xs, ee) -> return (x:xs, ee)
+      (x, (xs, e)) <- listItemContentsUntil (sourceColumn pos) (try (optional blankline >> indentWith indent >> museOrderedListMarker style >> continuation)) (([],) <$> end)
+      return (x:xs, e)
 
+-- | Parse an ordered list.
 orderedListUntil :: PandocMonad m
                  => MuseParser m a
                  -> MuseParser m (F Blocks, a)
@@ -612,10 +644,8 @@
 descriptionsUntil indent end = do
   void spaceChar <|> lookAhead eol
   updateState (\st -> st { museInPara = False })
-  (x, e) <- listItemContentsUntil indent (Right <$> try (optional blankline >> indentWith indent >> manyTill spaceChar (string "::") >> descriptionsUntil indent end)) (Left <$> end)
-  case e of
-    Right (xs, ee) -> return (x:xs, ee)
-    Left ee -> return ([x], ee)
+  (x, (xs, e)) <- listItemContentsUntil indent (try (optional blankline >> indentWith indent >> manyTill spaceChar (string "::") >> descriptionsUntil indent end)) (([],) <$> end)
+  return (x:xs, e)
 
 definitionListItemsUntil :: PandocMonad m
                          => Int
@@ -627,36 +657,30 @@
     continuation = try $ do
       pos <- getPosition
       term <- trimInlinesF . mconcat <$> manyTill (choice inlineList) (try $ string "::")
-      (x, e) <- descriptionsUntil (sourceColumn pos) ((Right <$> try (optional blankline >> indentWith indent >> continuation)) <|> (Left <$> end))
-      let xx = do
-            term' <- term
-            x' <- sequence x
-            return (term', x')
-      case e of
-        Left ee -> return ([xx], ee)
-        Right (xs, ee) -> return (xx:xs, ee)
+      (x, (xs, e)) <- descriptionsUntil (sourceColumn pos) (try (optional blankline >> indentWith indent >> continuation) <|> (([],) <$> end))
+      let xx = (,) <$> term <*> sequence x
+      return (xx:xs, e)
 
+-- | Parse a definition list.
 definitionListUntil :: PandocMonad m
-                    => MuseParser m a
+                    => MuseParser m a -- ^ Terminator parser
                     -> MuseParser m (F Blocks, a)
 definitionListUntil end = try $ do
   many spaceChar
   pos <- getPosition
   let indent = sourceColumn pos - 1
   guardDisabled Ext_amuse <|> guard (indent /= 0) -- Initial space is required by Amusewiki, but not Emacs Muse
-  (items, e) <- definitionListItemsUntil indent end
-  return (B.definitionList <$> sequence items, e)
+  first (fmap B.definitionList . sequence) <$> definitionListItemsUntil indent end
 
 anyListUntil :: PandocMonad m
-             => MuseParser m a
+             => MuseParser m a -- ^ Terminator parser
              -> MuseParser m (F Blocks, a)
 anyListUntil end =
   bulletListUntil end <|> orderedListUntil end <|> definitionListUntil end
 
---
--- tables
---
+-- *** Table parsers
 
+-- | Internal Muse table representation.
 data MuseTable = MuseTable
   { museTableCaption :: Inlines
   , museTableHeaders :: [[Blocks]]
@@ -664,10 +688,10 @@
   , museTableFooters :: [[Blocks]]
   }
 
-data MuseTableElement = MuseHeaderRow (F [Blocks])
-                      | MuseBodyRow   (F [Blocks])
-                      | MuseFooterRow (F [Blocks])
-                      | MuseCaption (F Inlines)
+data MuseTableElement = MuseHeaderRow [Blocks]
+                      | MuseBodyRow [Blocks]
+                      | MuseFooterRow [Blocks]
+                      | MuseCaption Inlines
 
 museToPandocTable :: MuseTable -> Blocks
 museToPandocTable (MuseTable caption headers body footers) =
@@ -677,73 +701,66 @@
         headRow = if null headers then [] else head headers
         rows = (if null headers then [] else tail headers) ++ body ++ footers
 
-museAppendElement :: MuseTable
-                  -> MuseTableElement
-                  -> F MuseTable
-museAppendElement tbl element =
+museAppendElement :: MuseTableElement
+                  -> MuseTable
+                  -> MuseTable
+museAppendElement element tbl =
   case element of
-    MuseHeaderRow row -> do
-      row' <- row
-      return tbl{ museTableHeaders = museTableHeaders tbl ++ [row'] }
-    MuseBodyRow row -> do
-      row' <- row
-      return tbl{ museTableRows = museTableRows tbl ++ [row'] }
-    MuseFooterRow row-> do
-      row' <- row
-      return tbl{ museTableFooters = museTableFooters tbl ++ [row'] }
-    MuseCaption inlines -> do
-      inlines' <- inlines
-      return tbl{ museTableCaption = inlines' }
+    MuseHeaderRow row -> tbl{ museTableHeaders = row : museTableHeaders tbl }
+    MuseBodyRow row -> tbl{ museTableRows = row : museTableRows tbl }
+    MuseFooterRow row -> tbl{ museTableFooters = row : museTableFooters tbl }
+    MuseCaption inlines -> tbl{ museTableCaption = inlines }
 
 tableCell :: PandocMonad m => MuseParser m (F Blocks)
 tableCell = try $ fmap B.plain . trimInlinesF . mconcat <$> manyTill inline (lookAhead cellEnd)
   where cellEnd = try $ void (many1 spaceChar >> char '|') <|> eol
 
-tableElements :: PandocMonad m => MuseParser m [MuseTableElement]
-tableElements = tableParseElement `sepEndBy1` eol
+tableElements :: PandocMonad m => MuseParser m (F [MuseTableElement])
+tableElements = sequence <$> (tableParseElement `sepEndBy1` eol)
 
-elementsToTable :: [MuseTableElement] -> F MuseTable
-elementsToTable = foldM museAppendElement emptyTable
+elementsToTable :: [MuseTableElement] -> MuseTable
+elementsToTable = foldr museAppendElement emptyTable
   where emptyTable = MuseTable mempty mempty mempty mempty
 
+-- | Parse a table.
 table :: PandocMonad m => MuseParser m (F Blocks)
-table = try $ do
-  rows <- tableElements
-  let tbl = elementsToTable rows
-  let pandocTbl = museToPandocTable <$> tbl :: F Blocks
-  return pandocTbl
+table = try $ fmap (museToPandocTable . elementsToTable) <$> tableElements
 
-tableParseElement :: PandocMonad m => MuseParser m MuseTableElement
+tableParseElement :: PandocMonad m => MuseParser m (F MuseTableElement)
 tableParseElement = tableParseHeader
                 <|> tableParseBody
                 <|> tableParseFooter
                 <|> tableParseCaption
 
-tableParseRow :: PandocMonad m => Int -> MuseParser m (F [Blocks])
+tableParseRow :: PandocMonad m
+              => Int -- ^ Number of separator characters
+              -> MuseParser m (F [Blocks])
 tableParseRow n = try $ do
   fields <- tableCell `sepBy2` fieldSep
   return $ sequence fields
     where p `sepBy2` sep = (:) <$> p <*> many1 (sep >> p)
           fieldSep = many1 spaceChar >> count n (char '|') >> (void (many1 spaceChar) <|> void (lookAhead newline))
 
-tableParseHeader :: PandocMonad m => MuseParser m MuseTableElement
-tableParseHeader = MuseHeaderRow <$> tableParseRow 2
+-- | Parse a table header row.
+tableParseHeader :: PandocMonad m => MuseParser m (F MuseTableElement)
+tableParseHeader = fmap MuseHeaderRow <$> tableParseRow 2
 
-tableParseBody :: PandocMonad m => MuseParser m MuseTableElement
-tableParseBody = MuseBodyRow <$> tableParseRow 1
+-- | Parse a table body row.
+tableParseBody :: PandocMonad m => MuseParser m (F MuseTableElement)
+tableParseBody = fmap MuseBodyRow <$> tableParseRow 1
 
-tableParseFooter :: PandocMonad m => MuseParser m MuseTableElement
-tableParseFooter = MuseFooterRow <$> tableParseRow 3
+-- | Parse a table footer row.
+tableParseFooter :: PandocMonad m => MuseParser m (F MuseTableElement)
+tableParseFooter = fmap MuseFooterRow <$> tableParseRow 3
 
-tableParseCaption :: PandocMonad m => MuseParser m MuseTableElement
+-- | Parse table caption.
+tableParseCaption :: PandocMonad m => MuseParser m (F MuseTableElement)
 tableParseCaption = try $ do
   many spaceChar
   string "|+"
-  MuseCaption <$> (trimInlinesF . mconcat <$> many1Till inline (string "+|"))
+  fmap MuseCaption <$> (trimInlinesF . mconcat <$> many1Till inline (string "+|"))
 
---
--- inline parsers
---
+-- ** Inline parsers
 
 inlineList :: PandocMonad m => [MuseParser m (F Inlines)]
 inlineList = [ whitespace
@@ -764,6 +781,7 @@
              , link
              , code
              , codeTag
+             , mathTag
              , inlineLiteralTag
              , str
              , symbol
@@ -772,28 +790,30 @@
 inline :: PandocMonad m => MuseParser m (F Inlines)
 inline = endline <|> choice inlineList <?> "inline"
 
+-- | Parse a soft break.
 endline :: PandocMonad m => MuseParser m (F Inlines)
 endline = try $ do
   newline
   notFollowedBy blankline
-  returnF B.softbreak
+  return $ return B.softbreak
 
 parseAnchor :: PandocMonad m => MuseParser m String
 parseAnchor = try $ do
   getPosition >>= \pos -> guard (sourceColumn pos == 1)
   char '#'
-  first <- letter
-  rest <- many (letter <|> digit)
-  skipMany spaceChar <|> void newline
-  return $ first:rest
+  (:) <$> letter <*> many (letter <|> digit <|> char '-')
 
 anchor :: PandocMonad m => MuseParser m (F Inlines)
 anchor = try $ do
   anchorId <- parseAnchor
+  skipMany spaceChar <|> void newline
   return $ return $ B.spanWith (anchorId, [], []) mempty
 
+-- | Parse a footnote reference.
 footnote :: PandocMonad m => MuseParser m (F Inlines)
 footnote = try $ do
+  inLink <- museInLink <$> getState
+  guard $ not inLink
   ref <- noteMarker
   return $ do
     notes <- asksF museNotes
@@ -801,7 +821,7 @@
       Nothing -> return $ B.str $ "[" ++ ref ++ "]"
       Just (_pos, contents) -> do
         st <- askF
-        let contents' = runF contents st { museNotes = M.empty }
+        let contents' = runF contents st { museNotes = M.delete ref (museNotes st) }
         return $ B.note contents'
 
 whitespace :: PandocMonad m => MuseParser m (F Inlines)
@@ -809,6 +829,7 @@
   skipMany1 spaceChar
   return $ return B.space
 
+-- | Parse @\<br>@ tag.
 br :: PandocMonad m => MuseParser m (F Inlines)
 br = try $ do
   string "<br>"
@@ -824,44 +845,54 @@
 enclosedInlines start end = try $
   trimInlinesF . mconcat <$> (enclosed (atStart start) end inline <* notFollowedBy (satisfy isLetter))
 
+-- | Parse an inline tag, such as @\<em>@ and @\<strong>@.
 inlineTag :: PandocMonad m
-          => (Inlines -> Inlines)
-          -> String
+          => String -- ^ Tag name
           -> MuseParser m (F Inlines)
-inlineTag f tag = try $ do
+inlineTag tag = try $ do
   htmlTag (~== TagOpen tag [])
-  res <- manyTill inline (void $ htmlTag (~== TagClose tag))
-  return $ f <$> mconcat res
-
-strongTag :: PandocMonad m => MuseParser m (F Inlines)
-strongTag = inlineTag B.strong "strong"
+  mconcat <$> manyTill inline (void $ htmlTag (~== TagClose tag))
 
+-- | Parse strong inline markup, indicated by @**@.
 strong :: PandocMonad m => MuseParser m (F Inlines)
 strong = fmap B.strong <$> emphasisBetween (string "**")
 
+-- | Parse emphasis inline markup, indicated by @*@.
 emph :: PandocMonad m => MuseParser m (F Inlines)
 emph = fmap B.emph <$> emphasisBetween (char '*')
 
+-- | Parse underline inline markup, indicated by @_@.
+-- Supported only in Emacs Muse mode, not Text::Amuse.
 underlined :: PandocMonad m => MuseParser m (F Inlines)
 underlined = do
   guardDisabled Ext_amuse -- Supported only by Emacs Muse
   fmap underlineSpan <$> emphasisBetween (char '_')
 
+-- | Parse @\<strong>@ tag.
+strongTag :: PandocMonad m => MuseParser m (F Inlines)
+strongTag = fmap B.strong <$> inlineTag "strong"
+
+-- | Parse @\<em>@ tag.
 emphTag :: PandocMonad m => MuseParser m (F Inlines)
-emphTag = inlineTag B.emph "em"
+emphTag = fmap B.emph <$> inlineTag "em"
 
+-- | Parse @\<sup>@ tag.
 superscriptTag :: PandocMonad m => MuseParser m (F Inlines)
-superscriptTag = inlineTag B.superscript "sup"
+superscriptTag = fmap B.superscript <$> inlineTag "sup"
 
+-- | Parse @\<sub>@ tag.
 subscriptTag :: PandocMonad m => MuseParser m (F Inlines)
-subscriptTag = inlineTag B.subscript "sub"
+subscriptTag = fmap B.subscript <$> inlineTag "sub"
 
+-- | Parse @\<del>@ tag.
 strikeoutTag :: PandocMonad m => MuseParser m (F Inlines)
-strikeoutTag = inlineTag B.strikeout "del"
+strikeoutTag = fmap B.strikeout <$> inlineTag "del"
 
+-- | Parse @\<verbatim>@ tag.
 verbatimTag :: PandocMonad m => MuseParser m (F Inlines)
 verbatimTag = return . B.text . snd <$> htmlElement "verbatim"
 
+-- | Parse @\<class>@ tag.
 classTag :: PandocMonad m => MuseParser m (F Inlines)
 classTag = do
   (TagOpen _ attrs, _) <- htmlTag (~== TagOpen "class" [])
@@ -869,11 +900,13 @@
   let classes = maybe [] words $ lookup "name" attrs
   return $ B.spanWith ("", classes, []) <$> mconcat res
 
+-- | Parse "~~" as nonbreaking space.
 nbsp :: PandocMonad m => MuseParser m (F Inlines)
 nbsp = try $ do
   string "~~"
   return $ return $ B.str "\160"
 
+-- | Parse code markup, indicated by @\'=\'@ characters.
 code :: PandocMonad m => MuseParser m (F Inlines)
 code = try $ do
   atStart $ char '='
@@ -884,11 +917,16 @@
   notFollowedBy $ satisfy isLetter
   return $ return $ B.code contents
 
+-- | Parse @\<code>@ tag.
 codeTag :: PandocMonad m => MuseParser m (F Inlines)
-codeTag = do
-  (attrs, content) <- htmlElement "code"
-  return $ return $ B.codeWith attrs content
+codeTag = return . uncurry B.codeWith <$> htmlElement "code"
 
+-- | Parse @\<math>@ tag.
+-- @\<math>@ tag is an Emacs Muse extension enabled by @(require 'muse-latex2png)@
+mathTag :: PandocMonad m => MuseParser m (F Inlines)
+mathTag = return . B.math . snd <$> htmlElement "math"
+
+-- | Parse inline @\<literal>@ tag as a raw inline.
 inlineLiteralTag :: PandocMonad m => MuseParser m (F Inlines)
 inlineLiteralTag =
   (return . rawInline) <$> htmlElement "literal"
@@ -898,39 +936,35 @@
     rawInline (attrs, content) = B.rawInline (format attrs) content
 
 str :: PandocMonad m => MuseParser m (F Inlines)
-str = do
-  result <- many1 alphaNum
-  updateLastStrPos
-  return $ return $ B.str result
+str = return . B.str <$> many1 alphaNum <* updateLastStrPos
 
 symbol :: PandocMonad m => MuseParser m (F Inlines)
 symbol = return . B.str <$> count 1 nonspaceChar
 
+-- | Parse a link or image.
 link :: PandocMonad m => MuseParser m (F Inlines)
 link = try $ do
   st <- getState
   guard $ not $ museInLink st
   setState $ st{ museInLink = True }
-  (url, title, content) <- linkText
+  (url, content) <- linkText
   updateState (\state -> state { museInLink = False })
   return $ case stripPrefix "URL:" url of
              Nothing -> if isImageUrl url
-                          then B.image url title <$> fromMaybe (return mempty) content
-                          else B.link url title <$> fromMaybe (return $ B.str url) content
-             Just url' -> B.link url' title <$> fromMaybe (return $ B.str url') content
+                          then B.image url "" <$> fromMaybe (return mempty) content
+                          else B.link url "" <$> fromMaybe (return $ B.str url) content
+             Just url' -> B.link url' "" <$> fromMaybe (return $ B.str url') content
     where -- Taken from muse-image-regexp defined in Emacs Muse file lisp/muse-regexps.el
           imageExtensions = [".eps", ".gif", ".jpg", ".jpeg", ".pbm", ".png", ".tiff", ".xbm", ".xpm"]
           isImageUrl = (`elem` imageExtensions) . takeExtension
 
 linkContent :: PandocMonad m => MuseParser m (F Inlines)
-linkContent = do
-  char '['
-  trimInlinesF . mconcat <$> many1Till inline (string "]")
+linkContent = char '[' >> trimInlinesF . mconcat <$> manyTill inline (string "]")
 
-linkText :: PandocMonad m => MuseParser m (String, String, Maybe (F Inlines))
+linkText :: PandocMonad m => MuseParser m (String, Maybe (F Inlines))
 linkText = do
   string "[["
-  url <- many1Till anyChar $ char ']'
+  url <- manyTill anyChar $ char ']'
   content <- optionMaybe linkContent
   char ']'
-  return (url, "", content)
+  return (url, content)
diff --git a/src/Text/Pandoc/Readers/OPML.hs b/src/Text/Pandoc/Readers/OPML.hs
--- a/src/Text/Pandoc/Readers/OPML.hs
+++ b/src/Text/Pandoc/Readers/OPML.hs
@@ -1,5 +1,34 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-# LANGUAGE FlexibleContexts #-}
+{-
+Copyright (C) 2013-2018 John MacFarlane <jgm@berkeley.edu>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+-}
+
+{- |
+   Module      : Text.Pandoc.Readers.OPML
+   Copyright   : Copyright (C) 2013-2018 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Conversion of OPML to 'Pandoc' document.
+-}
+
 module Text.Pandoc.Readers.OPML ( readOPML ) where
 import Prelude
 import Control.Monad.State.Strict
diff --git a/src/Text/Pandoc/Readers/RST.hs b/src/Text/Pandoc/Readers/RST.hs
--- a/src/Text/Pandoc/Readers/RST.hs
+++ b/src/Text/Pandoc/Readers/RST.hs
@@ -651,11 +651,15 @@
   skipMany spaceChar
   top <- many $ satisfy (/='\n')
              <|> try (char '\n' <*
-                      notFollowedBy' (rawFieldListItem 3) <*
-                      count 3 (char ' ') <*
+                      notFollowedBy' (rawFieldListItem 1) <*
+                      many1 (char ' ') <*
                       notFollowedBy blankline)
   newline
-  fields <- many $ rawFieldListItem 3
+  fields <- do
+    fieldIndent <- length <$> lookAhead (many (char ' '))
+    if fieldIndent == 0
+       then return []
+       else many $ rawFieldListItem fieldIndent
   body <- option "" $ try $ blanklines >> indentedBlock
   optional blanklines
   let body' = body ++ "\n\n"
@@ -1086,10 +1090,15 @@
 targetURI = do
   skipSpaces
   optional newline
-  contents <- many1 (try (many spaceChar >> newline >>
-                          many1 spaceChar >> noneOf " \t\n") <|> noneOf "\n")
+  contents <- trim <$>
+     many1 (satisfy (/='\n')
+     <|> try (newline >> many1 spaceChar >> noneOf " \t\n"))
   blanklines
-  return $ escapeURI $ trim contents
+  case reverse contents of
+       -- strip backticks
+       '_':'`':xs -> return (dropWhile (=='`') (reverse xs) ++ "_")
+       '_':_      -> return contents
+       _          -> return (escapeURI contents)
 
 substKey :: PandocMonad m => RSTParser m ()
 substKey = try $ do
diff --git a/src/Text/Pandoc/Readers/TWiki.hs b/src/Text/Pandoc/Readers/TWiki.hs
--- a/src/Text/Pandoc/Readers/TWiki.hs
+++ b/src/Text/Pandoc/Readers/TWiki.hs
@@ -1,8 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-# LANGUAGE FlexibleContexts     #-}
-{-# LANGUAGE FlexibleInstances    #-}
-{-# LANGUAGE RelaxedPolyRec       #-}
-{-# LANGUAGE TypeSynonymInstances #-}
+{-# LANGUAGE FlexibleContexts  #-}
+{-# LANGUAGE RelaxedPolyRec    #-}
+
 -- RelaxedPolyRec needed for inlinesBetween on GHC < 7
 {-
   Copyright (C) 2014 Alexander Sulfrian <alexander.sulfrian@fu-berlin.de>
diff --git a/src/Text/Pandoc/Readers/Textile.hs b/src/Text/Pandoc/Readers/Textile.hs
--- a/src/Text/Pandoc/Readers/Textile.hs
+++ b/src/Text/Pandoc/Readers/Textile.hs
@@ -395,7 +395,7 @@
                              (toprow:rest) | any (fst . fst) toprow ->
                                 (toprow, rest)
                              _ -> (mempty, rawrows)
-  let nbOfCols = max (length headers) (length $ head rows)
+  let nbOfCols = maximum $ map length (headers:rows)
   let aligns = map minimum $ transpose $ map (map (snd . fst)) (headers:rows)
   return $ B.table caption
     (zip aligns (replicate nbOfCols 0.0))
diff --git a/src/Text/Pandoc/Readers/TikiWiki.hs b/src/Text/Pandoc/Readers/TikiWiki.hs
--- a/src/Text/Pandoc/Readers/TikiWiki.hs
+++ b/src/Text/Pandoc/Readers/TikiWiki.hs
@@ -1,9 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-# LANGUAGE FlexibleContexts     #-}
-{-# LANGUAGE FlexibleInstances    #-}
-{-# LANGUAGE OverloadedStrings    #-}
-{-# LANGUAGE RelaxedPolyRec       #-}
-{-# LANGUAGE TypeSynonymInstances #-}
+{-# LANGUAGE FlexibleContexts  #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE RelaxedPolyRec    #-}
 
 {- |
    Module      : Text.Pandoc.Readers.TikiWiki
diff --git a/src/Text/Pandoc/Templates.hs b/src/Text/Pandoc/Templates.hs
--- a/src/Text/Pandoc/Templates.hs
+++ b/src/Text/Pandoc/Templates.hs
@@ -1,8 +1,4 @@
-{-# LANGUAGE NoImplicitPrelude #-}
-{-# LANGUAGE FlexibleInstances    #-}
-
-{-# LANGUAGE OverloadedStrings    #-}
-{-# LANGUAGE TypeSynonymInstances #-}
+{-# LANGUAGE OverloadedStrings #-}
 {-
 Copyright (C) 2009-2018 John MacFarlane <jgm@berkeley.edu>
 
diff --git a/src/Text/Pandoc/Writers/CommonMark.hs b/src/Text/Pandoc/Writers/CommonMark.hs
--- a/src/Text/Pandoc/Writers/CommonMark.hs
+++ b/src/Text/Pandoc/Writers/CommonMark.hs
@@ -116,7 +116,7 @@
 blockToNodes opts (RawBlock fmt xs) ns
   | fmt == Format "html" && isEnabled Ext_raw_html opts
               = return (node (HTML_BLOCK (T.pack xs)) [] : ns)
-  | fmt == Format "latex" || fmt == Format "tex" && isEnabled Ext_raw_tex opts
+  | (fmt == Format "latex" || fmt == Format "tex") && isEnabled Ext_raw_tex opts
               = return (node (CUSTOM_BLOCK (T.pack xs) T.empty) [] : ns)
   | otherwise = return ns
 blockToNodes opts (BlockQuote bs) ns = do
diff --git a/src/Text/Pandoc/Writers/EPUB.hs b/src/Text/Pandoc/Writers/EPUB.hs
--- a/src/Text/Pandoc/Writers/EPUB.hs
+++ b/src/Text/Pandoc/Writers/EPUB.hs
@@ -403,6 +403,12 @@
                       writeHtmlStringForEPUB version o
   metadata <- getEPUBMetadata opts meta
 
+  let plainTitle = case docTitle' meta of
+                        [] -> case epubTitle metadata of
+                                   []    -> "UNTITLED"
+                                   (x:_) -> titleText x
+                        x  -> stringify x
+
   -- stylesheet
   stylesheets <- case epubStylesheets metadata of
                       [] -> (\x -> [B.fromChunks [x]]) <$>
@@ -440,6 +446,7 @@
                        cpContent <- lift $ writeHtml
                             opts'{ writerVariables =
                                     ("coverpage","true"):
+                                    ("pagetitle",plainTitle):
                                      cssvars True ++ vars }
                             (Pandoc meta [RawBlock (Format "html") $ "<div id=\"cover-image\">\n<img src=\"../media/" ++ coverImage ++ "\" alt=\"cover image\" />\n</div>"])
                        imgContent <- lift $ P.readFileLazy img
@@ -452,6 +459,7 @@
   -- title page
   tpContent <- lift $ writeHtml opts'{
                                   writerVariables = ("titlepage","true"):
+                                  ("pagetitle",plainTitle):
                                   cssvars True ++ vars }
                                (Pandoc meta [])
   tpEntry <- mkEntry "text/title_page.xhtml" tpContent
@@ -604,11 +612,6 @@
                                      $ eRelativePath ent),
                             ("media-type", fromMaybe "" $
                                   getMimeType $ eRelativePath ent)] $ ()
-  let plainTitle = case docTitle' meta of
-                        [] -> case epubTitle metadata of
-                                   []    -> "UNTITLED"
-                                   (x:_) -> titleText x
-                        x  -> stringify x
 
   let tocTitle = fromMaybe plainTitle $
                    metaValueToString <$> lookupMeta "toc-title" meta
@@ -749,7 +752,10 @@
           where titElements = parseXML titRendered
                 titRendered = case P.runPure
                                (writeHtmlStringForEPUB version
-                                 opts{ writerTemplate = Nothing }
+                                 opts{ writerTemplate = Nothing
+                                     , writerVariables =
+                                       ("pagetitle",plainTitle):
+                                       writerVariables opts}
                                  (Pandoc nullMeta
                                    [Plain $ walk clean tit])) of
                                 Left _  -> TS.pack $ stringify tit
diff --git a/src/Text/Pandoc/Writers/FB2.hs b/src/Text/Pandoc/Writers/FB2.hs
--- a/src/Text/Pandoc/Writers/FB2.hs
+++ b/src/Text/Pandoc/Writers/FB2.hs
@@ -46,7 +46,7 @@
 import qualified Data.ByteString.Char8 as B8
 import Data.Char (isAscii, isControl, isSpace, toLower)
 import Data.Either (lefts, rights)
-import Data.List (intercalate, intersperse, isPrefixOf, stripPrefix)
+import Data.List (intercalate, isPrefixOf, stripPrefix)
 import Data.Text (Text, pack)
 import Network.HTTP (urlEncode)
 import Text.XML.Light
@@ -118,6 +118,9 @@
   bt <- booktitle meta'
   let as = authors meta'
   dd <- docdate meta'
+  annotation <- case lookupMeta "abstract" meta' of
+                  Just (MetaBlocks bs) -> (list . el "annotation") <$> cMapM blockToXml bs
+                  _ -> pure mempty
   let lang = case lookupMeta "lang" meta' of
                Just (MetaInlines [Str s]) -> [el "lang" $ iso639 s]
                Just (MetaString s)        -> [el "lang" $ iso639 s]
@@ -132,7 +135,7 @@
                     Just (MetaString s) -> coverimage s
                     _       -> return []
   return $ el "description"
-    [ el "title-info" (genre : (bt ++ as ++ dd ++ lang))
+    [ el "title-info" (genre : (bt ++ annotation ++ as ++ dd ++ lang))
     , el "document-info" (el "program-used" "pandoc" : coverpage)
     ]
 
@@ -180,7 +183,7 @@
 renderSection level (ttl, body) = do
     title <- if null ttl
             then return []
-            else return . list . el "title" . formatTitle $ ttl
+            else list . el "title" <$> formatTitle ttl
     content <- if hasSubsections body
                then renderSections (level + 1) body
                else cMapM blockToXml body
@@ -189,11 +192,9 @@
     hasSubsections = any isHeaderBlock
 
 -- | Only <p> and <empty-line> are allowed within <title> in FB2.
-formatTitle :: [Inline] -> [Content]
+formatTitle :: PandocMonad m => [Inline] -> FBM m [Content]
 formatTitle inlines =
-  let lns = split isLineBreak inlines
-      lns' = map (el "p" . cMap plain) lns
-  in  intersperse (el "empty-line" ()) lns'
+  cMapM (blockToXml . Para) $ split (== LineBreak) inlines
 
 split :: (a -> Bool) -> [a] -> [[a]]
 split _ [] = []
@@ -313,9 +314,6 @@
 footnoteID :: Int -> String
 footnoteID i = "n" ++ show i
 
-linkID :: Int -> String
-linkID i = "l" ++ show i
-
 -- | Convert a block-level Pandoc's element to FictionBook XML representation.
 blockToXml :: PandocMonad m => Block -> FBM m [Content]
 blockToXml (Plain ss) = cMapM toXml ss  -- FIXME: can lead to malformed FB2
@@ -367,10 +365,7 @@
   -- should not occur after hierarchicalize, except inside lists/blockquotes
   report $ BlockNotRendered h
   return []
-blockToXml HorizontalRule = return
-                            [ el "empty-line" ()
-                            , el "p" (txt (replicate 10 '—'))
-                            , el "empty-line" () ]
+blockToXml HorizontalRule = return [ el "empty-line" () ]
 blockToXml (Table caption aligns _ headers rows) = do
     hd <- mkrow "th" headers aligns
     bd <- mapM (\r -> mkrow "td" r aligns) rows
@@ -400,7 +395,7 @@
 plainToPara (Plain inlines : rest) =
     Para inlines : plainToPara rest
 plainToPara (Para inlines : rest) =
-    Para inlines : Plain [LineBreak] : plainToPara rest
+    Para inlines : HorizontalRule : plainToPara rest -- HorizontalRule will be converted to <empty-line />
 plainToPara (p:rest) = p : plainToPara rest
 
 -- Simulate increased indentation level. Will not really work
@@ -451,29 +446,15 @@
 toXml (Cite _ ss) = cMapM toXml ss  -- FIXME: support citation styles
 toXml (Code _ s) = return [el "code" s]
 toXml Space = return [txt " "]
-toXml SoftBreak = return [txt " "]
-toXml LineBreak = return [el "empty-line" ()]
+toXml SoftBreak = return [txt "\n"]
+toXml LineBreak = return [txt "\n"]
 toXml (Math _ formula) = insertMath InlineImage formula
 toXml il@(RawInline _ _) = do
   report $ InlineNotRendered il
   return []  -- raw TeX and raw HTML are suppressed
-toXml (Link _ text (url,ttl)) = do
-  fns <- footnotes `liftM` get
-  let n = 1 + length fns
-  let ln_id = linkID n
-  let ln_ref = list . el "sup" . txt $ "[" ++ show n ++ "]"
+toXml (Link _ text (url,_)) = do
   ln_text <- cMapM toXml text
-  let ln_desc =
-          let ttl' = dropWhile isSpace ttl
-          in if null ttl'
-             then list . el "p" $ el "code" url
-             else list . el "p" $ [ txt (ttl' ++ ": "), el "code" url ]
-  modify (\s -> s { footnotes = (n, ln_id, ln_desc) : fns })
-  return $ ln_text ++
-         [ el "a"
-                  ( [ attr ("l","href") ('#':ln_id)
-                    , uattr "type" "note" ]
-                  , ln_ref) ]
+  return [ el "a" ( [ attr ("l","href") url ], ln_text) ]
 toXml img@Image{} = insertImage InlineImage img
 toXml (Note bs) = do
   fns <- footnotes `liftM` get
diff --git a/src/Text/Pandoc/Writers/HTML.hs b/src/Text/Pandoc/Writers/HTML.hs
--- a/src/Text/Pandoc/Writers/HTML.hs
+++ b/src/Text/Pandoc/Writers/HTML.hs
@@ -260,10 +260,6 @@
   notes <- footnoteSection opts (reverse (stNotes st))
   let thebody = blocks' >> notes
   let  math = case writerHTMLMathMethod opts of
-                      LaTeXMathML (Just url) ->
-                         H.script ! A.src (toValue url)
-                                  ! A.type_ "text/javascript"
-                                  $ mempty
                       MathJax url
                         | slideVariant /= RevealJsSlides ->
                         -- mathjax is handled via a special plugin in revealjs
@@ -274,10 +270,6 @@
                                             preEscapedString
                                             "MathJax.Hub.Queue([\"Typeset\",MathJax.Hub]);"
                                          _ -> mempty
-                      JsMath (Just url) ->
-                         H.script ! A.src (toValue url)
-                                  ! A.type_ "text/javascript"
-                                  $ mempty
                       KaTeX url -> do
                          H.script !
                            A.src (toValue $ url ++ "katex.min.js") $ mempty
@@ -478,7 +470,12 @@
   html5 <- gets stHtml5
   slideVariant <- gets stSlideVariant
   let hrtag = if html5 then H5.hr else H.hr
+  epubVersion <- gets stEPUBVersion
   let container x
+        | html5
+        , epubVersion == Just EPUB3
+                = H5.section ! A.class_ "footnotes"
+                             ! customAttribute "epub:type" "footnotes" $ x
         | html5 = H5.section ! A.class_ "footnotes" $ x
         | slideVariant /= NoSlides = H.div ! A.class_ "footnotes slide" $ x
         | otherwise = H.div ! A.class_ "footnotes" $ x
@@ -1019,19 +1016,6 @@
       let mathClass = toValue $ ("math " :: String) ++
                       if t == InlineMath then "inline" else "display"
       case writerHTMLMathMethod opts of
-           LaTeXMathML _ ->
-              -- putting LaTeXMathML in container with class "LaTeX" prevents
-              -- non-math elements on the page from being treated as math by
-              -- the javascript
-              return $ H.span ! A.class_ "LaTeX" $
-                     case t of
-                       InlineMath  -> toHtml ("$" ++ str ++ "$")
-                       DisplayMath -> toHtml ("$$" ++ str ++ "$$")
-           JsMath _ -> do
-              let m = preEscapedString str
-              return $ case t of
-                       InlineMath  -> H.span ! A.class_ mathClass $ m
-                       DisplayMath -> H.div ! A.class_ mathClass $ m
            WebTeX url -> do
               let imtag = if html5 then H5.img else H.img
               let m = imtag ! A.style "vertical-align:middle"
@@ -1042,10 +1026,6 @@
               return $ case t of
                         InlineMath  -> m
                         DisplayMath -> brtag >> m >> brtag
-           GladTeX ->
-              return $ case t of
-                         InlineMath -> preEscapedString $ "<EQ ENV=\"math\">" ++ str ++ "</EQ>"
-                         DisplayMath -> preEscapedString $ "<EQ ENV=\"displaymath\">" ++ str ++ "</EQ>"
            MathML -> do
               let conf = useShortEmptyTags (const False)
                            defaultConfigPP
diff --git a/src/Text/Pandoc/Writers/ICML.hs b/src/Text/Pandoc/Writers/ICML.hs
--- a/src/Text/Pandoc/Writers/ICML.hs
+++ b/src/Text/Pandoc/Writers/ICML.hs
@@ -1,6 +1,6 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-# LANGUAGE FlexibleContexts    #-}
-{-# LANGUAGE OverloadedStrings   #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE ScopedTypeVariables #-}
 
 {- |
diff --git a/src/Text/Pandoc/Writers/LaTeX.hs b/src/Text/Pandoc/Writers/LaTeX.hs
--- a/src/Text/Pandoc/Writers/LaTeX.hs
+++ b/src/Text/Pandoc/Writers/LaTeX.hs
@@ -678,6 +678,7 @@
   let enum = text $ "enum" ++ map toLower (toRomanNumeral oldlevel)
   let stylecommand
         | numstyle == DefaultStyle && numdelim == DefaultDelim = empty
+        | beamer && numstyle == Decimal && numdelim == Period = empty
         | beamer = brackets (todelim exemplar)
         | otherwise = "\\def" <> "\\label" <> enum <>
           braces (todelim $ tostyle enum)
@@ -1035,7 +1036,7 @@
                                Nothing -> ""
         inNote <- gets stInNote
         when inNote $ modify $ \s -> s{ stVerbInNote = True }
-        let chr = case "!\"&'()*,-./:;?@_" \\ str of
+        let chr = case "!\"'()*,-./:;?@" \\ str of
                        (c:_) -> c
                        []    -> '!'
         let str' = escapeStringUsing (backslashEscapes "\\{}%~_&") str
diff --git a/src/Text/Pandoc/Writers/Markdown.hs b/src/Text/Pandoc/Writers/Markdown.hs
--- a/src/Text/Pandoc/Writers/Markdown.hs
+++ b/src/Text/Pandoc/Writers/Markdown.hs
@@ -732,7 +732,10 @@
                   then empty
                   else border <> cr <> head'
   let body = if multiline
-                then vsep rows'
+                then vsep rows' $$
+                     if length rows' < 2
+                        then blankline -- #4578
+                        else empty
                 else vcat rows'
   let bottom = if headless
                   then underline
diff --git a/src/Text/Pandoc/Writers/Ms.hs b/src/Text/Pandoc/Writers/Ms.hs
--- a/src/Text/Pandoc/Writers/Ms.hs
+++ b/src/Text/Pandoc/Writers/Ms.hs
@@ -40,7 +40,7 @@
 import Prelude
 import Control.Monad.State.Strict
 import Data.Char (isLower, isUpper, toUpper, ord)
-import Data.List (intercalate, intersperse, sort)
+import Data.List (intercalate, intersperse)
 import qualified Data.Map as Map
 import Data.Maybe (catMaybes, fromMaybe)
 import Data.Text (Text)
@@ -68,6 +68,7 @@
                                , stNotes         :: [Note]
                                , stSmallCaps     :: Bool
                                , stHighlighting  :: Bool
+                               , stInHeader      :: Bool
                                , stFontFeatures  :: Map.Map Char Bool
                                }
 
@@ -77,6 +78,7 @@
                                 , stNotes         = []
                                 , stSmallCaps     = False
                                 , stHighlighting  = False
+                                , stInHeader      = False
                                 , stFontFeatures  = Map.fromList [
                                                        ('I',False)
                                                      , ('B',False)
@@ -135,7 +137,6 @@
               [ ('\160', "\\~")
               , ('\'', "\\[aq]")
               , ('`', "\\`")
-              , ('\8217', "'")
               , ('"', "\\[dq]")
               , ('\x2014', "\\[em]")
               , ('\x2013', "\\[en]")
@@ -218,11 +219,16 @@
           -> Block         -- ^ Block element
           -> MS m Doc
 blockToMs _ Null = return empty
-blockToMs opts (Div _ bs) = do
+blockToMs opts (Div (ident,_,_) bs) = do
+  let anchor = if null ident
+                  then empty
+                  else nowrap $
+                         text ".pdfhref M "
+                         <> doubleQuotes (text (toAscii ident))
   setFirstPara
   res <- blockListToMs opts bs
   setFirstPara
-  return res
+  return $ anchor $$ res
 blockToMs opts (Plain inlines) =
   liftM vcat $ mapM (inlineListToMs' opts) $ splitSentences inlines
 blockToMs opts (Para [Image attr alt (src,_tit)])
@@ -260,7 +266,9 @@
   return $ text ".HLINE"
 blockToMs opts (Header level (ident,classes,_) inlines) = do
   setFirstPara
+  modify $ \st -> st{ stInHeader = True }
   contents <- inlineListToMs' opts $ map breakToSpace inlines
+  modify $ \st -> st{ stInHeader = False }
   let (heading, secnum) = if writerNumberSections opts &&
                               "unnumbered" `notElem` classes
                              then (".NH", "\\*[SN]")
@@ -555,8 +563,15 @@
 fontChange :: PandocMonad m => MS m Doc
 fontChange = do
   features <- gets stFontFeatures
-  let filling = sort [c | (c,True) <- Map.toList features]
-  return $ text $ "\\f[" ++ filling ++ "]"
+  inHeader <- gets stInHeader
+  let filling = ['C' | fromMaybe False $ Map.lookup 'C' features] ++
+                ['B' | inHeader ||
+                       fromMaybe False (Map.lookup 'B' features)] ++
+                ['I' | fromMaybe False $ Map.lookup 'I' features]
+  return $
+    if null filling
+       then text "\\f[R]"
+       else text $ "\\f[" ++ filling ++ "]"
 
 withFontFeature :: PandocMonad m => Char -> MS m Doc -> MS m Doc
 withFontFeature c action = do
@@ -641,7 +656,10 @@
            modify (\st -> st{ stHighlighting = True })
            return h
 
+-- This is used for PDF anchors.
 toAscii :: String -> String
-toAscii = concatMap (\c -> case toAsciiChar c of
-                                     Nothing -> 'u':show (ord c)
-                                     Just c' -> [c'])
+toAscii = concatMap
+  (\c -> case toAsciiChar c of
+              Nothing -> '_':'u':show (ord c) ++ "_"
+              Just '/' -> '_':'u':show (ord c) ++ "_" -- see #4515
+              Just c' -> [c'])
diff --git a/src/Text/Pandoc/Writers/Muse.hs b/src/Text/Pandoc/Writers/Muse.hs
--- a/src/Text/Pandoc/Writers/Muse.hs
+++ b/src/Text/Pandoc/Writers/Muse.hs
@@ -44,7 +44,10 @@
 -}
 module Text.Pandoc.Writers.Muse (writeMuse) where
 import Prelude
+import Control.Monad.Reader
 import Control.Monad.State.Strict
+import Data.Char (isSpace, isDigit, isAsciiUpper, isAsciiLower)
+import Data.Default
 import Data.Text (Text)
 import Data.List (intersperse, transpose, isInfixOf)
 import System.FilePath (takeExtension)
@@ -60,34 +63,54 @@
 import qualified Data.Set as Set
 
 type Notes = [[Block]]
+
+type Muse m = ReaderT WriterEnv (StateT WriterState m)
+
+data WriterEnv =
+  WriterEnv { envOptions :: WriterOptions
+            , envTopLevel :: Bool
+            , envInsideBlock :: Bool
+            , envInlineStart :: Bool
+            , envInsideLinkDescription :: Bool -- ^ Escape ] if True
+            , envAfterSpace :: Bool
+            , envOneLine :: Bool -- ^ True if newlines are not allowed
+            }
+
 data WriterState =
   WriterState { stNotes       :: Notes
-              , stOptions     :: WriterOptions
-              , stTopLevel    :: Bool
-              , stInsideBlock :: Bool
               , stIds         :: Set.Set String
               }
 
+instance Default WriterState
+  where def = WriterState { stNotes = []
+                          , stIds = Set.empty
+                          }
+
+evalMuse :: PandocMonad m => Muse m a -> WriterEnv -> WriterState -> m a
+evalMuse document env = evalStateT $ runReaderT document env
+
 -- | Convert Pandoc to Muse.
 writeMuse :: PandocMonad m
           => WriterOptions
           -> Pandoc
           -> m Text
 writeMuse opts document =
-  let st = WriterState { stNotes = []
-                       , stOptions = opts
-                       , stTopLevel = True
-                       , stInsideBlock = False
-                       , stIds = Set.empty
-                       }
-  in evalStateT (pandocToMuse document) st
+  evalMuse (pandocToMuse document) env def
+  where env = WriterEnv { envOptions = opts
+                        , envTopLevel = True
+                        , envInsideBlock = False
+                        , envInlineStart = True
+                        , envInsideLinkDescription = False
+                        , envAfterSpace = False
+                        , envOneLine = False
+                        }
 
 -- | Return Muse representation of document.
 pandocToMuse :: PandocMonad m
              => Pandoc
-             -> StateT WriterState m Text
+             -> Muse m Text
 pandocToMuse (Pandoc meta blocks) = do
-  opts <- gets stOptions
+  opts <- asks envOptions
   let colwidth = if writerWrapText opts == WrapAuto
                     then Just $ writerColumns opts
                     else Nothing
@@ -98,7 +121,7 @@
                (fmap render' . inlineListToMuse)
                meta
   body <- blockListToMuse blocks
-  notes <- liftM (reverse . stNotes) get >>= notesToMuse
+  notes <- fmap (reverse . stNotes) get >>= notesToMuse
   let main = render colwidth $ body $+$ notes
   let context = defField "body" main metadata
   case writerTemplate opts of
@@ -110,7 +133,7 @@
 catWithBlankLines :: PandocMonad m
                   => [Block]       -- ^ List of block elements
                   -> Int           -- ^ Number of blank lines
-                  -> StateT WriterState m Doc
+                  -> Muse m Doc
 catWithBlankLines (b : bs) n = do
   b' <- blockToMuse b
   bs' <- flatBlockListToMuse bs
@@ -118,10 +141,10 @@
 catWithBlankLines _ _ = error "Expected at least one block"
 
 -- | Convert list of Pandoc block elements to Muse
--- | without setting stTopLevel.
+-- | without setting envTopLevel.
 flatBlockListToMuse :: PandocMonad m
                 => [Block]       -- ^ List of block elements
-                -> StateT WriterState m Doc
+                -> Muse m Doc
 flatBlockListToMuse bs@(BulletList _ : BulletList _ : _) = catWithBlankLines bs 2
 flatBlockListToMuse bs@(OrderedList (_, style1, _) _ : OrderedList (_, style2, _) _ : _) =
   catWithBlankLines bs (if style1' == style2' then 2 else 0)
@@ -137,28 +160,22 @@
 -- | Convert list of Pandoc block elements to Muse.
 blockListToMuse :: PandocMonad m
                 => [Block]       -- ^ List of block elements
-                -> StateT WriterState m Doc
-blockListToMuse blocks = do
-  oldState <- get
-  modify $ \s -> s { stTopLevel = not $ stInsideBlock s
-                   , stInsideBlock = True
-                   }
-  result <- flatBlockListToMuse blocks
-  modify $ \s -> s { stTopLevel = stTopLevel oldState
-                   , stInsideBlock = stInsideBlock oldState
-                   }
-  return result
+                -> Muse m Doc
+blockListToMuse =
+  local (\env -> env { envTopLevel = not (envInsideBlock env)
+                     , envInsideBlock = True
+                     }) . flatBlockListToMuse
 
 -- | Convert Pandoc block element to Muse.
 blockToMuse :: PandocMonad m
             => Block         -- ^ Block element
-            -> StateT WriterState m Doc
-blockToMuse (Plain inlines) = inlineListToMuse inlines
+            -> Muse m Doc
+blockToMuse (Plain inlines) = inlineListToMuse' inlines
 blockToMuse (Para inlines) = do
-  contents <- inlineListToMuse inlines
+  contents <- inlineListToMuse' inlines
   return $ contents <> blankline
 blockToMuse (LineBlock lns) = do
-  lns' <- mapM inlineListToMuse lns
+  lns' <- local (\env -> env { envOneLine = True }) $ mapM inlineListToMuse lns
   return $ nowrap $ vcat (map (text "> " <>) lns') <> blankline
 blockToMuse (CodeBlock (_,_,_) str) =
   return $ "<example>" $$ text str $$ "</example>" $$ blankline
@@ -175,52 +192,48 @@
 blockToMuse (OrderedList (start, style, _) items) = do
   let markers = take (length items) $ orderedListMarkers
                                       (start, style, Period)
-  let maxMarkerLength = maximum $ map length markers
-  let markers' = map (\m -> let s = maxMarkerLength - length m
-                            in  m ++ replicate s ' ') markers
-  contents <- zipWithM orderedListItemToMuse markers' items
+  contents <- zipWithM orderedListItemToMuse markers items
   -- ensure that sublists have preceding blank line
-  topLevel <- gets stTopLevel
+  topLevel <- asks envTopLevel
   return $ cr $$ (if topLevel then nest 1 else id) (vcat contents) $$ blankline
   where orderedListItemToMuse :: PandocMonad m
                               => String   -- ^ marker for list item
                               -> [Block]  -- ^ list item (list of blocks)
-                              -> StateT WriterState m Doc
+                              -> Muse m Doc
         orderedListItemToMuse marker item = do
           contents <- blockListToMuse item
           return $ hang (length marker + 1) (text marker <> space) contents
 blockToMuse (BulletList items) = do
   contents <- mapM bulletListItemToMuse items
   -- ensure that sublists have preceding blank line
-  topLevel <- gets stTopLevel
+  topLevel <- asks envTopLevel
   return $ cr $$ (if topLevel then nest 1 else id) (vcat contents) $$ blankline
   where bulletListItemToMuse :: PandocMonad m
                              => [Block]
-                             -> StateT WriterState m Doc
+                             -> Muse m Doc
         bulletListItemToMuse item = do
           contents <- blockListToMuse item
           return $ hang 2 "- " contents
 blockToMuse (DefinitionList items) = do
   contents <- mapM definitionListItemToMuse items
   -- ensure that sublists have preceding blank line
-  topLevel <- gets stTopLevel
+  topLevel <- asks envTopLevel
   return $ cr $$ (if topLevel then nest 1 else id) (vcat contents) $$ blankline
   where definitionListItemToMuse :: PandocMonad m
                                  => ([Inline], [[Block]])
-                                 -> StateT WriterState m Doc
+                                 -> Muse m Doc
         definitionListItemToMuse (label, defs) = do
-          label' <- inlineListToMuse label
-          contents <- liftM vcat $ mapM descriptionToMuse defs
+          label' <- local (\env -> env { envOneLine = True, envAfterSpace = True }) $ inlineListToMuse' label
+          contents <- vcat <$> mapM descriptionToMuse defs
           let ind = offset label'
           return $ hang ind label' contents
         descriptionToMuse :: PandocMonad m
                           => [Block]
-                          -> StateT WriterState m Doc
+                          -> Muse m Doc
         descriptionToMuse desc = hang 4 " :: " <$> blockListToMuse desc
 blockToMuse (Header level (ident,_,_) inlines) = do
-  opts <- gets stOptions
-  contents <- inlineListToMuse inlines
-
+  opts <- asks envOptions
+  contents <- local (\env -> env { envOneLine = True }) $ inlineListToMuse' inlines
   ids <- gets stIds
   let autoId = uniqueIdent inlines ids
   modify $ \st -> st{ stIds = Set.insert autoId ids }
@@ -229,8 +242,7 @@
                  then empty
                  else "#" <> text ident <> cr
   let header' = text $ replicate level '*'
-  return $ blankline <> nowrap (header' <> space <> contents)
-                 $$ attr' <> blankline
+  return $ blankline <> attr' $$ nowrap (header' <> space <> contents) <> blankline
 -- https://www.gnu.org/software/emacs-muse/manual/muse.html#Horizontal-Rules-and-Anchors
 blockToMuse HorizontalRule = return $ blankline $$ "----" $$ blankline
 blockToMuse (Table caption _ _ headers rows) =  do
@@ -263,18 +275,18 @@
 -- | Return Muse representation of notes.
 notesToMuse :: PandocMonad m
             => Notes
-            -> StateT WriterState m Doc
-notesToMuse notes = liftM vsep (zipWithM noteToMuse [1 ..] notes)
+            -> Muse m Doc
+notesToMuse notes = vsep <$> zipWithM noteToMuse [1 ..] notes
 
 -- | Return Muse representation of a note.
 noteToMuse :: PandocMonad m
            => Int
            -> [Block]
-           -> StateT WriterState m Doc
-noteToMuse num note = do
-  contents <- blockListToMuse note
-  let marker = "[" ++ show num ++ "] "
-  return $ hang (length marker) (text marker) contents
+           -> Muse m Doc
+noteToMuse num note =
+  hang (length marker) (text marker) <$> blockListToMuse note
+  where
+    marker = "[" ++ show num ++ "] "
 
 -- | Escape special characters for Muse.
 escapeString :: String -> String
@@ -283,14 +295,40 @@
   substitute "</verbatim>" "<</verbatim><verbatim>/verbatim>" s ++
   "</verbatim>"
 
+startsWithMarker :: (Char -> Bool) -> String -> Bool
+startsWithMarker f (' ':xs) = startsWithMarker f xs
+startsWithMarker f (x:xs) =
+  f x && (startsWithMarker f xs || startsWithDot xs)
+  where
+    startsWithDot ['.'] = True
+    startsWithDot ('.':c:_) = isSpace c
+    startsWithDot _ = False
+startsWithMarker _ [] = False
+
 -- | Escape special characters for Muse if needed.
-conditionalEscapeString :: String -> String
-conditionalEscapeString s =
-  if any (`elem` ("#*<=>[]|" :: String)) s ||
+containsFootnotes :: String -> Bool
+containsFootnotes = p
+  where p ('[':xs) = q xs || p xs
+        p (_:xs) = p xs
+        p "" = False
+        q (x:xs)
+          | x `elem` ("123456789"::String) = r xs || p xs
+          | otherwise = p xs
+        q [] = False
+        r ('0':xs) = r xs || p xs
+        r xs = s xs || q xs || p xs
+        s (']':_) = True
+        s (_:xs) = p xs
+        s [] = False
+
+conditionalEscapeString :: Bool -> String -> String
+conditionalEscapeString isInsideLinkDescription s =
+  if any (`elem` ("#*<=|" :: String)) s ||
      "::" `isInfixOf` s ||
-     "----" `isInfixOf` s ||
      "~~" `isInfixOf` s ||
-     "-" == s
+     "[[" `isInfixOf` s ||
+     ("]" `isInfixOf` s && isInsideLinkDescription) ||
+     containsFootnotes s
     then escapeString s
     else s
 
@@ -311,6 +349,13 @@
 replaceSmallCaps (SmallCaps lst) = Emph lst
 replaceSmallCaps x = x
 
+removeKeyValues :: Inline -> Inline
+removeKeyValues (Code (i, cls, _) xs) = Code (i, cls, []) xs
+-- Do not remove attributes from Link
+-- Do not remove attributes, such as "width", from Image
+removeKeyValues (Span (i, cls, _) xs) = Span (i, cls, []) xs
+removeKeyValues x = x
+
 normalizeInlineList :: [Inline] -> [Inline]
 normalizeInlineList (Str "" : xs)
   = normalizeInlineList xs
@@ -334,8 +379,7 @@
   = normalizeInlineList $ Code nullAttr (x1 ++ x2) : ils
 normalizeInlineList (RawInline f1 x1 : RawInline f2 x2 : ils) | f1 == f2
   = normalizeInlineList $ RawInline f1 (x1 ++ x2) : ils
-normalizeInlineList (Span a1 x1 : Span a2 x2 : ils) | a1 == a2
-  = normalizeInlineList $ Span a1 (x1 ++ x2) : ils
+-- Do not join Span's during normalization
 normalizeInlineList (x:xs) = x : normalizeInlineList xs
 normalizeInlineList [] = []
 
@@ -345,21 +389,77 @@
 fixNotes (SoftBreak : n@Note{} : rest) = Str " " : n : fixNotes rest
 fixNotes (x:xs) = x : fixNotes xs
 
--- | Convert list of Pandoc inline elements to Muse.
-inlineListToMuse :: PandocMonad m
+urlEscapeBrackets :: String -> String
+urlEscapeBrackets (']':xs) = '%':'5':'D':urlEscapeBrackets xs
+urlEscapeBrackets (x:xs) = x:urlEscapeBrackets xs
+urlEscapeBrackets [] = []
+
+isHorizontalRule :: String -> Bool
+isHorizontalRule s = length s >= 4 && all (== '-') s
+
+startsWithSpace :: String -> Bool
+startsWithSpace (x:_) = isSpace x
+startsWithSpace [] = False
+
+fixOrEscape :: Bool -> Inline -> Bool
+fixOrEscape sp (Str "-") = sp
+fixOrEscape sp (Str ";") = not sp
+fixOrEscape _ (Str ">") = True
+fixOrEscape sp (Str s) = (sp && (startsWithMarker isDigit s ||
+                                startsWithMarker isAsciiLower s ||
+                                startsWithMarker isAsciiUpper s))
+                         || isHorizontalRule s || startsWithSpace s
+fixOrEscape _ Space = True
+fixOrEscape _ SoftBreak = True
+fixOrEscape _ _ = False
+
+-- | Convert list of Pandoc inline elements to Muse
+renderInlineList :: PandocMonad m
                  => [Inline]
-                 -> StateT WriterState m Doc
-inlineListToMuse lst = do
-  lst' <- normalizeInlineList <$> preprocessInlineList (map replaceSmallCaps lst)
-  if null lst'
-    then pure "<verbatim></verbatim>"
-    else hcat <$> mapM inlineToMuse (fixNotes lst')
+                 -> Muse m Doc
+renderInlineList [] = do
+  start <- asks envInlineStart
+  pure $ if start then "<verbatim></verbatim>" else ""
+renderInlineList (x:xs) = do
+  start <- asks envInlineStart
+  afterSpace <- asks envAfterSpace
+  topLevel <- asks envTopLevel
+  r <- inlineToMuse x
+  opts <- asks envOptions
+  let isNewline = (x == SoftBreak && writerWrapText opts == WrapPreserve) || x == LineBreak
+  lst' <- local (\env -> env { envInlineStart = isNewline
+                             , envAfterSpace = x == Space || (not topLevel && isNewline)
+                             }) $ renderInlineList xs
+  if start && fixOrEscape afterSpace x
+    then pure (text "<verbatim></verbatim>" <> r <> lst')
+    else pure (r <> lst')
 
+-- | Normalize and convert list of Pandoc inline elements to Muse.
+inlineListToMuse'' :: PandocMonad m
+                   => Bool
+                   -> [Inline]
+                   -> Muse m Doc
+inlineListToMuse'' start lst = do
+  lst' <- (normalizeInlineList . fixNotes) <$> preprocessInlineList (map (removeKeyValues . replaceSmallCaps) lst)
+  topLevel <- asks envTopLevel
+  afterSpace <- asks envAfterSpace
+  local (\env -> env { envInlineStart = start
+                     , envAfterSpace = afterSpace || (start && not topLevel)
+                     }) $ renderInlineList lst'
+
+inlineListToMuse' :: PandocMonad m => [Inline] -> Muse m Doc
+inlineListToMuse' = inlineListToMuse'' True
+
+inlineListToMuse :: PandocMonad m => [Inline] -> Muse m Doc
+inlineListToMuse = inlineListToMuse'' False
+
 -- | Convert Pandoc inline element to Muse.
 inlineToMuse :: PandocMonad m
              => Inline
-             -> StateT WriterState m Doc
-inlineToMuse (Str str) = return $ text $ conditionalEscapeString str
+             -> Muse m Doc
+inlineToMuse (Str str) = do
+  insideLink <- asks envInsideLinkDescription
+  return $ text $ conditionalEscapeString insideLink str
 inlineToMuse (Emph lst) = do
   contents <- inlineListToMuse lst
   return $ "<em>" <> contents <> "</em>"
@@ -391,35 +491,38 @@
   fail "Math should be expanded before normalization"
 inlineToMuse (RawInline (Format f) str) =
   return $ "<literal style=\"" <> text f <> "\">" <> text str <> "</literal>"
-inlineToMuse LineBreak = return $ "<br>" <> cr
+inlineToMuse LineBreak = do
+  oneline <- asks envOneLine
+  return $ if oneline then "<br>" else "<br>" <> cr
 inlineToMuse Space = return space
 inlineToMuse SoftBreak = do
-  wrapText <- gets $ writerWrapText . stOptions
-  return $ if wrapText == WrapPreserve then cr else space
+  oneline <- asks envOneLine
+  wrapText <- asks $ writerWrapText . envOptions
+  return $ if not oneline && wrapText == WrapPreserve then cr else space
 inlineToMuse (Link _ txt (src, _)) =
   case txt of
         [Str x] | escapeURI x == src ->
              return $ "[[" <> text (escapeLink x) <> "]]"
-        _ -> do contents <- inlineListToMuse txt
+        _ -> do contents <- local (\env -> env { envInsideLinkDescription = True }) $ inlineListToMuse txt
                 return $ "[[" <> text (escapeLink src) <> "][" <> contents <> "]]"
-  where escapeLink lnk = if isImageUrl lnk then "URL:" ++ lnk else lnk
+  where escapeLink lnk = if isImageUrl lnk then "URL:" ++ urlEscapeBrackets lnk else urlEscapeBrackets lnk
         -- Taken from muse-image-regexp defined in Emacs Muse file lisp/muse-regexps.el
         imageExtensions = [".eps", ".gif", ".jpg", ".jpeg", ".pbm", ".png", ".tiff", ".xbm", ".xpm"]
         isImageUrl = (`elem` imageExtensions) . takeExtension
 inlineToMuse (Image attr alt (source,'f':'i':'g':':':title)) =
   inlineToMuse (Image attr alt (source,title))
 inlineToMuse (Image attr inlines (source, title)) = do
-  opts <- gets stOptions
-  alt <- inlineListToMuse inlines
+  opts <- asks envOptions
+  alt <- local (\env -> env { envInsideLinkDescription = True }) $ inlineListToMuse inlines
   let title' = if null title
                   then if null inlines
                           then ""
                           else "[" <> alt <> "]"
-                  else "[" <> text title <> "]"
+                  else "[" <> text (conditionalEscapeString True title) <> "]"
   let width = case dimension Width attr of
                 Just (Percent x) | isEnabled Ext_amuse opts -> " " ++ show (round x :: Integer)
                 _ -> ""
-  return $ "[[" <> text (source ++ width) <> "]" <> title' <> "]"
+  return $ "[[" <> text (urlEscapeBrackets source ++ width) <> "]" <> title' <> "]"
 inlineToMuse (Note contents) = do
   -- add to notes in state
   notes <- gets stNotes
@@ -431,6 +534,8 @@
   let anchorDoc = if null anchor
                      then mempty
                      else text ('#':anchor) <> space
-  return $ anchorDoc <> if null names
-                           then contents
-                           else "<class name=\"" <> text (head names) <> "\">" <> contents <> "</class>"
+  return $ anchorDoc <> (if null inlines && not (null anchor)
+                         then mempty
+                         else (if null names
+                               then "<class>"
+                               else "<class name=\"" <> text (head names) <> "\">") <> contents <> "</class>")
diff --git a/src/Text/Pandoc/Writers/Powerpoint/Output.hs b/src/Text/Pandoc/Writers/Powerpoint/Output.hs
--- a/src/Text/Pandoc/Writers/Powerpoint/Output.hs
+++ b/src/Text/Pandoc/Writers/Powerpoint/Output.hs
@@ -58,7 +58,7 @@
 import qualified Data.ByteString.Lazy as BL
 import Text.Pandoc.Writers.OOXML
 import qualified Data.Map as M
-import Data.Maybe (mapMaybe, listToMaybe, fromMaybe, isJust, maybeToList, catMaybes)
+import Data.Maybe (mapMaybe, listToMaybe, fromMaybe, maybeToList, catMaybes)
 import Text.Pandoc.ImageSize
 import Control.Applicative ((<|>))
 import System.FilePath.Glob
@@ -283,8 +283,9 @@
 makeSpeakerNotesMap :: Presentation -> M.Map Int Int
 makeSpeakerNotesMap (Presentation _ slides) =
   M.fromList $ (mapMaybe f $ slides `zip` [1..]) `zip` [1..]
-  where f (Slide _ _ Nothing, _) = Nothing
-        f (Slide _ _ (Just _), n)  = Just n
+  where f (Slide _ _ notes, n) = if notes == mempty
+                                 then Nothing
+                                 else Just n
 
 presentationToArchive :: PandocMonad m => WriterOptions -> Presentation -> m Archive
 presentationToArchive opts pres = do
@@ -324,13 +325,11 @@
 -- Check to see if the presentation has speaker notes. This will
 -- influence whether we import the notesMaster template.
 presHasSpeakerNotes :: Presentation -> Bool
-presHasSpeakerNotes (Presentation _ slides) = any isJust $ map slideSpeakerNotes slides
+presHasSpeakerNotes (Presentation _ slides) = not $ all (mempty ==) $ map slideSpeakerNotes slides
 
 curSlideHasSpeakerNotes :: PandocMonad m => P m Bool
-curSlideHasSpeakerNotes = do
-  sldId <- asks envCurSlideId
-  notesIdMap <- asks envSpeakerNotesIdMap
-  return $ isJust $ M.lookup sldId notesIdMap
+curSlideHasSpeakerNotes =
+  M.member <$> asks envCurSlideId <*> asks envSpeakerNotesIdMap
 
 --------------------------------------------------
 
@@ -341,17 +340,9 @@
         (TitleSlide _)          -> "ppt/slideLayouts/slideLayout3.xml"
         (ContentSlide _ _)      -> "ppt/slideLayouts/slideLayout2.xml"
         (TwoColumnSlide _ _ _)    -> "ppt/slideLayouts/slideLayout4.xml"
+  refArchive <- asks envRefArchive
   distArchive <- asks envDistArchive
-  root <- case findEntryByPath layoutpath distArchive of
-        Just e -> case parseXMLDoc $ UTF8.toStringLazy $ fromEntry e of
-                    Just element -> return $ element
-                    Nothing      -> throwError $
-                                    PandocSomeError $
-                                    layoutpath ++ " corrupt in reference file"
-        Nothing -> throwError $
-                   PandocSomeError $
-                   layoutpath ++ " missing in reference file"
-  return root
+  parseXml refArchive distArchive layoutpath
 
 shapeHasId :: NameSpaces -> String -> Element -> Bool
 shapeHasId ns ident element
@@ -1010,6 +1001,14 @@
       filterChild findPhType spTreeElem
   | otherwise = Nothing
 
+-- Like the above, but it tries a number of different placeholder types
+getShapeByPlaceHolderTypes :: NameSpaces -> Element -> [String] -> Maybe Element
+getShapeByPlaceHolderTypes _ _ [] = Nothing
+getShapeByPlaceHolderTypes ns spTreeElem (s:ss) =
+  case getShapeByPlaceHolderType ns spTreeElem s of
+    Just element -> Just element
+    Nothing -> getShapeByPlaceHolderTypes ns spTreeElem ss
+
 getShapeByPlaceHolderIndex :: NameSpaces -> Element -> String -> Maybe Element
 getShapeByPlaceHolderIndex ns spTreeElem phIdx
   | isElem ns "p" "spTree" spTreeElem =
@@ -1024,12 +1023,12 @@
   | otherwise = Nothing
 
 
-nonBodyTextToElement :: PandocMonad m => Element -> String -> [ParaElem] -> P m Element
-nonBodyTextToElement layout phType paraElements
+nonBodyTextToElement :: PandocMonad m => Element -> [String] -> [ParaElem] -> P m Element
+nonBodyTextToElement layout phTypes paraElements
   | ns <- elemToNameSpaces layout
   , Just cSld <- findChild (elemName ns "p" "cSld") layout
   , Just spTree <- findChild (elemName ns "p" "spTree") cSld
-  , Just sp <- getShapeByPlaceHolderType ns spTree phType = do
+  , Just sp <- getShapeByPlaceHolderTypes ns spTree phTypes = do
       let hdrPara = Paragraph def paraElements
       element <- paragraphToElement hdrPara
       let txBody = mknode "p:txBody" [] $
@@ -1044,7 +1043,7 @@
   | ns <- elemToNameSpaces layout
   , Just cSld <- findChild (elemName ns "p" "cSld") layout
   , Just spTree <- findChild (elemName ns "p" "spTree") cSld = do
-      element <- nonBodyTextToElement layout "title" hdrShape
+      element <- nonBodyTextToElement layout ["title"] hdrShape
       let hdrShapeElements = if null hdrShape
                              then []
                              else [element]
@@ -1062,7 +1061,7 @@
   | ns <- elemToNameSpaces layout
   , Just cSld <- findChild (elemName ns "p" "cSld") layout
   , Just spTree <- findChild (elemName ns "p" "spTree") cSld = do
-      element <- nonBodyTextToElement layout "title" hdrShape
+      element <- nonBodyTextToElement layout ["title"] hdrShape
       let hdrShapeElements = if null hdrShape
                              then []
                              else [element]
@@ -1086,7 +1085,7 @@
   | ns <- elemToNameSpaces layout
   , Just cSld <- findChild (elemName ns "p" "cSld") layout
   , Just spTree <- findChild (elemName ns "p" "spTree") cSld = do
-      element <- nonBodyTextToElement layout "title" titleElems
+      element <- nonBodyTextToElement layout ["title", "ctrTitle"] titleElems
       let titleShapeElements = if null titleElems
                                then []
                                else [element]
@@ -1100,15 +1099,15 @@
   , Just spTree <- findChild (elemName ns "p" "spTree") cSld = do
       titleShapeElements <- if null titleElems
                             then return []
-                            else sequence [nonBodyTextToElement layout "ctrTitle" titleElems]
+                            else sequence [nonBodyTextToElement layout ["ctrTitle"] titleElems]
       let combinedAuthorElems = intercalate [Break] authorsElems
           subtitleAndAuthorElems = intercalate [Break, Break] [subtitleElems, combinedAuthorElems]
       subtitleShapeElements <- if null subtitleAndAuthorElems
                                then return []
-                               else sequence [nonBodyTextToElement layout "subTitle" subtitleAndAuthorElems]
+                               else sequence [nonBodyTextToElement layout ["subTitle"] subtitleAndAuthorElems]
       dateShapeElements <- if null dateElems
                            then return []
-                           else sequence [nonBodyTextToElement layout "dt" dateElems]
+                           else sequence [nonBodyTextToElement layout ["dt"] dateElems]
       return $ replaceNamedChildren ns "p" "sp"
         (titleShapeElements ++ subtitleShapeElements ++ dateShapeElements)
         spTree
@@ -1160,18 +1159,9 @@
 
 getNotesMaster :: PandocMonad m => P m Element
 getNotesMaster = do
-  let notesMasterPath = "ppt/notesMasters/notesMaster1.xml"
+  refArchive <- asks envRefArchive
   distArchive <- asks envDistArchive
-  root <- case findEntryByPath notesMasterPath distArchive of
-        Just e -> case parseXMLDoc $ UTF8.toStringLazy $ fromEntry e of
-                    Just element -> return $ element
-                    Nothing      -> throwError $
-                                    PandocSomeError $
-                                    notesMasterPath ++ " corrupt in reference file"
-        Nothing -> throwError $
-                   PandocSomeError $
-                   notesMasterPath ++ " missing in reference file"
-  return root
+  parseXml refArchive distArchive "ppt/notesMasters/notesMaster1.xml"
 
 getSlideNumberFieldId :: PandocMonad m => Element -> P m String
 getSlideNumberFieldId notesMaster
@@ -1272,42 +1262,40 @@
   ]
 
 slideToSpeakerNotesElement :: PandocMonad m => Slide -> P m (Maybe Element)
-slideToSpeakerNotesElement slide
-  | Slide _ _ mbNotes <- slide
-  , Just (SpeakerNotes paras) <- mbNotes = do
-      master <- getNotesMaster
-      fieldId  <- getSlideNumberFieldId master
-      num <- slideNum slide
-      let imgShape = speakerNotesSlideImage
-          sldNumShape = speakerNotesSlideNumber num fieldId
-      bodyShape <- speakerNotesBody paras
-      return $ Just $
-        mknode "p:notes"
-        [ ("xmlns:a", "http://schemas.openxmlformats.org/drawingml/2006/main")
-        , ("xmlns:r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships")
-        , ("xmlns:p", "http://schemas.openxmlformats.org/presentationml/2006/main")
-        ] [ mknode "p:cSld" []
-            [ mknode "p:spTree" []
-              [ mknode "p:nvGrpSpPr" []
-                [ mknode "p:cNvPr" [("id", "1"), ("name", "")] ()
-                , mknode "p:cNvGrpSpPr" [] ()
-                , mknode "p:nvPr" [] ()
-                ]
-            , mknode "p:grpSpPr" []
-              [ mknode "a:xfrm" []
-                [ mknode "a:off" [("x", "0"), ("y", "0")] ()
-                , mknode "a:ext" [("cx", "0"), ("cy", "0")] ()
-                , mknode "a:chOff" [("x", "0"), ("y", "0")] ()
-                , mknode "a:chExt" [("cx", "0"), ("cy", "0")] ()
-                ]
-              ]
-            , imgShape
-            , bodyShape
-            , sldNumShape
+slideToSpeakerNotesElement (Slide _ _ (SpeakerNotes [])) = return Nothing
+slideToSpeakerNotesElement slide@(Slide _ _ (SpeakerNotes paras)) = do
+  master <- getNotesMaster
+  fieldId  <- getSlideNumberFieldId master
+  num <- slideNum slide
+  let imgShape = speakerNotesSlideImage
+      sldNumShape = speakerNotesSlideNumber num fieldId
+  bodyShape <- speakerNotesBody paras
+  return $ Just $
+    mknode "p:notes"
+    [ ("xmlns:a", "http://schemas.openxmlformats.org/drawingml/2006/main")
+    , ("xmlns:r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships")
+    , ("xmlns:p", "http://schemas.openxmlformats.org/presentationml/2006/main")
+    ] [ mknode "p:cSld" []
+        [ mknode "p:spTree" []
+          [ mknode "p:nvGrpSpPr" []
+            [ mknode "p:cNvPr" [("id", "1"), ("name", "")] ()
+            , mknode "p:cNvGrpSpPr" [] ()
+            , mknode "p:nvPr" [] ()
             ]
+          , mknode "p:grpSpPr" []
+            [ mknode "a:xfrm" []
+              [ mknode "a:off" [("x", "0"), ("y", "0")] ()
+              , mknode "a:ext" [("cx", "0"), ("cy", "0")] ()
+              , mknode "a:chOff" [("x", "0"), ("y", "0")] ()
+              , mknode "a:chExt" [("cx", "0"), ("cy", "0")] ()
+              ]
             ]
+          , imgShape
+          , bodyShape
+          , sldNumShape
           ]
-slideToSpeakerNotesElement _ = return Nothing
+        ]
+      ]
 
 -----------------------------------------------------------------------
 
@@ -1482,23 +1470,22 @@
       _ -> return Nothing
 
 slideToSpeakerNotesRelElement :: PandocMonad m => Slide -> P m (Maybe Element)
-slideToSpeakerNotesRelElement slide
-  | Slide _ _ mbNotes <- slide
-  , Just _ <- mbNotes = do
-      idNum <- slideNum slide
-      return $ Just $
-        mknode "Relationships"
-        [("xmlns", "http://schemas.openxmlformats.org/package/2006/relationships")]
-        [ mknode "Relationship" [ ("Id", "rId2")
-                                , ("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide")
-                                , ("Target", "../slides/slide" ++ show idNum ++ ".xml")
-                                ] ()
-        , mknode "Relationship" [ ("Id", "rId1")
-                                , ("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster")
-                                , ("Target", "../notesMasters/notesMaster1.xml")
-                                ] ()
-        ]
-slideToSpeakerNotesRelElement _ = return Nothing
+slideToSpeakerNotesRelElement (Slide _ _ (SpeakerNotes [])) = return Nothing
+slideToSpeakerNotesRelElement slide@(Slide _ _ _) = do
+  idNum <- slideNum slide
+  return $ Just $
+    mknode "Relationships"
+    [("xmlns", "http://schemas.openxmlformats.org/package/2006/relationships")]
+    [ mknode "Relationship" [ ("Id", "rId2")
+                            , ("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide")
+                            , ("Target", "../slides/slide" ++ show idNum ++ ".xml")
+                            ] ()
+    , mknode "Relationship" [ ("Id", "rId1")
+                            , ("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster")
+                            , ("Target", "../notesMasters/notesMaster1.xml")
+                            ] ()
+    ]
+
 
 slideToSpeakerNotesRelEntry :: PandocMonad m => Slide -> P m (Maybe Entry)
 slideToSpeakerNotesRelEntry slide = do
diff --git a/src/Text/Pandoc/Writers/Powerpoint/Presentation.hs b/src/Text/Pandoc/Writers/Powerpoint/Presentation.hs
--- a/src/Text/Pandoc/Writers/Powerpoint/Presentation.hs
+++ b/src/Text/Pandoc/Writers/Powerpoint/Presentation.hs
@@ -1,5 +1,6 @@
-{-# LANGUAGE NoImplicitPrelude #-}
-{-# LANGUAGE PatternGuards #-}
+{-# LANGUAGE NoImplicitPrelude          #-}
+{-# LANGUAGE PatternGuards              #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
 
 {-
 Copyright (C) 2017-2018 Jesse Rosenthal <jrosenthal@jhu.edu>
@@ -112,7 +113,7 @@
                                , stAnchorMap :: M.Map String SlideId
                                , stSlideIdSet :: S.Set SlideId
                                , stLog :: [LogMessage]
-                               , stSpeakerNotesMap :: M.Map SlideId [[Paragraph]]
+                               , stSpeakerNotes :: SpeakerNotes
                                } deriving (Show, Eq)
 
 instance Default WriterState where
@@ -121,7 +122,7 @@
                     -- we reserve this s
                     , stSlideIdSet = reservedSlideIds
                     , stLog = []
-                    , stSpeakerNotesMap = mempty
+                    , stSpeakerNotes = mempty
                     }
 
 metadataSlideId :: SlideId
@@ -185,7 +186,7 @@
 
 data Slide = Slide { slideId :: SlideId
                    , slideLayout :: Layout
-                   , slideSpeakerNotes :: Maybe SpeakerNotes
+                   , slideSpeakerNotes :: SpeakerNotes
                    } deriving (Show, Eq)
 
 newtype SlideId = SlideId String
@@ -195,7 +196,7 @@
 -- designed mainly for one textbox, so we'll just put in the contents
 -- of that textbox, to avoid other shapes that won't work as well.
 newtype SpeakerNotes = SpeakerNotes {fromSpeakerNotes :: [Paragraph]}
-  deriving (Show, Eq)
+  deriving (Show, Eq, Monoid, Semigroup)
 
 data Layout = MetadataSlide { metadataSlideTitle :: [ParaElem]
                             , metadataSlideSubtitle :: [ParaElem]
@@ -375,10 +376,21 @@
     modify $ \st -> st { stNoteIds = M.insert curNoteId blks notes }
     local (\env -> env{envRunProps = (envRunProps env){rLink = Just $ InternalTarget endNotesSlideId}}) $
       inlineToParElems $ Superscript [Str $ show curNoteId]
-inlineToParElems (Span _ ils) = concatMapM inlineToParElems ils
+inlineToParElems (Span _ ils) = inlinesToParElems ils
+inlineToParElems (Quoted quoteType ils) =
+  inlinesToParElems $ [Str open] ++ ils ++ [Str close]
+  where (open, close) = case quoteType of
+                          SingleQuote -> ("\x2018", "\x2019")
+                          DoubleQuote -> ("\x201C", "\x201D")
 inlineToParElems (RawInline _ _) = return []
-inlineToParElems _ = return []
+inlineToParElems (Cite _ ils) = inlinesToParElems ils
+-- Note: we shouldn't reach this, because images should be handled at
+-- the shape level, but should that change in the future, we render
+-- the alt text.
+inlineToParElems (Image _ alt _) = inlinesToParElems alt
 
+
+
 isListType :: Block -> Bool
 isListType (OrderedList _ _) = True
 isListType (BulletList _) = True
@@ -400,10 +412,7 @@
 noteSize = 18
 
 blockToParagraphs :: Block -> Pres [Paragraph]
-blockToParagraphs (Plain ils) = do
-  parElems <- inlinesToParElems ils
-  pProps <- asks envParaProps
-  return [Paragraph pProps parElems]
+blockToParagraphs (Plain ils) = blockToParagraphs (Para ils)
 blockToParagraphs (Para ils) = do
   parElems <- inlinesToParElems ils
   pProps <- asks envParaProps
@@ -476,16 +485,6 @@
         definition <- concatMapM (blockToParagraphs . BlockQuote) blksLst
         return $ term ++ definition
   concatMapM go entries
-blockToParagraphs (Div (_, ["notes"], _) blks) =
-  local (\env -> env{envInSpeakerNotes=True}) $ do
-  sldId <- asks envCurSlideId
-  spkNotesMap <- gets stSpeakerNotesMap
-  paras <- concatMapM blockToParagraphs blks
-  let spkNotesMap' = case M.lookup sldId spkNotesMap of
-        Just lst -> M.insert sldId (paras : lst) spkNotesMap
-        Nothing  -> M.insert sldId [paras] spkNotesMap
-  modify $ \st -> st{stSpeakerNotesMap = spkNotesMap'}
-  return []
 blockToParagraphs (Div _ blks)  = concatMapM blockToParagraphs blks
 blockToParagraphs blk = do
   addLogMessage $ BlockNotRendered blk
@@ -528,14 +527,9 @@
 withAttr _ sp = sp
 
 blockToShape :: Block -> Pres Shape
-blockToShape (Plain (il:_)) | Image attr ils (url, _) <- il =
-      (withAttr attr . Pic def url) <$> inlinesToParElems ils
+blockToShape (Plain ils) = blockToShape (Para ils)
 blockToShape (Para (il:_))  | Image attr ils (url, _) <- il =
       (withAttr attr . Pic def url) <$> inlinesToParElems ils
-blockToShape (Plain (il:_)) | Link _ (il':_) target <- il
-                            , Image attr ils (url, _) <- il' =
-      (withAttr attr . Pic def {picPropLink = Just $ ExternalTarget target} url) <$>
-      inlinesToParElems ils
 blockToShape (Para (il:_))  | Link _ (il':_) target <- il
                             , Image attr ils (url, _) <- il' =
       (withAttr attr . Pic def{picPropLink = Just $ ExternalTarget target} url) <$>
@@ -559,7 +553,6 @@
 
 combineShapes :: [Shape] -> [Shape]
 combineShapes [] = []
-combineShapes[s] = [s]
 combineShapes (pic@Pic{} : ss) = pic : combineShapes ss
 combineShapes (TextBox [] : ss) = combineShapes ss
 combineShapes (s : TextBox [] : ss) = combineShapes (s : ss)
@@ -567,6 +560,10 @@
   combineShapes $ TextBox ((p:ps) ++ (p':ps')) : ss
 combineShapes (s:ss) = s : combineShapes ss
 
+isNotesDiv :: Block -> Bool
+isNotesDiv (Div (_, ["notes"], _) _) = True
+isNotesDiv _ = False
+
 blocksToShapes :: [Block] -> Pres [Shape]
 blocksToShapes blks = combineShapes <$> mapM blockToShape blks
 
@@ -590,64 +587,60 @@
 splitBlocks' cur acc (Plain ils : blks) = splitBlocks' cur acc (Para ils : blks)
 splitBlocks' cur acc (Para (il:ils) : blks) | isImage il = do
   slideLevel <- asks envSlideLevel
+  let (nts, blks') = if null ils
+                     then span isNotesDiv blks
+                     else ([], blks)
   case cur of
     [Header n _ _] | n == slideLevel ->
                             splitBlocks' []
-                            (acc ++ [cur ++ [Para [il]]])
-                            (if null ils then blks else Para ils : blks)
+                            (acc ++ [cur ++ [Para [il]] ++ nts])
+                            (if null ils then blks' else Para ils : blks')
     _ -> splitBlocks' []
-         (acc ++ (if null cur then [] else [cur]) ++ [[Para [il]]])
-         (if null ils then blks else Para ils : blks)
+         (acc ++ (if null cur then [] else [cur]) ++ [[Para [il]] ++ nts])
+         (if null ils then blks' else Para ils : blks')
 splitBlocks' cur acc (tbl@Table{} : blks) = do
   slideLevel <- asks envSlideLevel
+  let (nts, blks') = span isNotesDiv blks
   case cur of
     [Header n _ _] | n == slideLevel ->
-                            splitBlocks' [] (acc ++ [cur ++ [tbl]]) blks
-    _ ->  splitBlocks' [] (acc ++ (if null cur then [] else [cur]) ++ [[tbl]]) blks
+                            splitBlocks' [] (acc ++ [cur ++ [tbl] ++ nts]) blks'
+    _ ->  splitBlocks' [] (acc ++ (if null cur then [] else [cur]) ++ [[tbl] ++ nts]) blks'
 splitBlocks' cur acc (d@(Div (_, classes, _) _): blks) | "columns" `elem` classes =  do
   slideLevel <- asks envSlideLevel
+  let (nts, blks') = span isNotesDiv blks
   case cur of
     [Header n _ _] | n == slideLevel ->
-                            splitBlocks' [] (acc ++ [cur ++ [d]]) blks
-    _ ->  splitBlocks' [] (acc ++ (if null cur then [] else [cur]) ++ [[d]]) blks
+                            splitBlocks' [] (acc ++ [cur ++ [d] ++ nts]) blks'
+    _ ->  splitBlocks' [] (acc ++ (if null cur then [] else [cur]) ++ [[d] ++ nts]) blks'
 splitBlocks' cur acc (blk : blks) = splitBlocks' (cur ++ [blk]) acc blks
 
 splitBlocks :: [Block] -> Pres [[Block]]
 splitBlocks = splitBlocks' [] []
 
-getSpeakerNotes :: Pres (Maybe SpeakerNotes)
-getSpeakerNotes = do
-  sldId <- asks envCurSlideId
-  spkNtsMap <- gets stSpeakerNotesMap
-  return $ (SpeakerNotes . concat . reverse) <$> M.lookup sldId spkNtsMap
-
-blocksToSlide' :: Int -> [Block] -> Pres Slide
-blocksToSlide' lvl (Header n (ident, _, _) ils : blks)
+blocksToSlide' :: Int -> [Block] -> SpeakerNotes -> Pres Slide
+blocksToSlide' lvl (Header n (ident, _, _) ils : blks) spkNotes
   | n < lvl = do
       registerAnchorId ident
       sldId <- asks envCurSlideId
       hdr <- inlinesToParElems ils
-      return $ Slide sldId TitleSlide {titleSlideHeader = hdr} Nothing
+      return $ Slide sldId TitleSlide {titleSlideHeader = hdr} spkNotes
   | n == lvl = do
       registerAnchorId ident
       hdr <- inlinesToParElems ils
       -- Now get the slide without the header, and then add the header
       -- in.
-      slide <- blocksToSlide' lvl blks
+      slide <- blocksToSlide' lvl blks spkNotes
       let layout = case slideLayout slide of
             ContentSlide _ cont          -> ContentSlide hdr cont
             TwoColumnSlide _ contL contR -> TwoColumnSlide hdr contL contR
             layout'                     -> layout'
       return $ slide{slideLayout = layout}
-blocksToSlide' _ (blk : blks)
+blocksToSlide' _ (blk : blks) spkNotes
   | Div (_, classes, _) divBlks <- blk
   , "columns" `elem` classes
   , Div (_, clsL, _) blksL : Div (_, clsR, _) blksR : remaining <- divBlks
   , "column" `elem` clsL, "column" `elem` clsR = do
-      unless (null blks)
-        (mapM (addLogMessage . BlockNotRendered) blks >> return ())
-      unless (null remaining)
-        (mapM (addLogMessage . BlockNotRendered) remaining >> return ())
+      mapM_ (addLogMessage . BlockNotRendered) (blks ++ remaining)
       mbSplitBlksL <- splitBlocks blksL
       mbSplitBlksR <- splitBlocks blksR
       let blksL' = case mbSplitBlksL of
@@ -665,8 +658,8 @@
                        , twoColumnSlideLeft = shapesL
                        , twoColumnSlideRight = shapesR
                        }
-        Nothing
-blocksToSlide' _ (blk : blks) = do
+        spkNotes
+blocksToSlide' _ (blk : blks) spkNotes = do
       inNoteSlide <- asks envInNoteSlide
       shapes <- if inNoteSlide
                 then forceFontSize noteSize $ blocksToShapes (blk : blks)
@@ -678,8 +671,8 @@
         ContentSlide { contentSlideHeader = []
                      , contentSlideContent = shapes
                      }
-        Nothing
-blocksToSlide' _ [] = do
+        spkNotes
+blocksToSlide' _ [] spkNotes = do
   sldId <- asks envCurSlideId
   return $
     Slide
@@ -687,14 +680,32 @@
     ContentSlide { contentSlideHeader = []
                  , contentSlideContent = []
                  }
-    Nothing
+    spkNotes
 
+handleNotes :: Block -> Pres ()
+handleNotes (Div (_, ["notes"], _) blks) =
+  local (\env -> env{envInSpeakerNotes=True}) $ do
+  spNotes <- SpeakerNotes <$> concatMapM blockToParagraphs blks
+  modify $ \st -> st{stSpeakerNotes = (stSpeakerNotes st) <> spNotes}
+handleNotes _ = return ()
+
+handleAndFilterNotes' :: [Block] -> Pres [Block]
+handleAndFilterNotes' blks = do
+  mapM_ handleNotes blks
+  return $ filter (not . isNotesDiv) blks
+
+handleAndFilterNotes :: [Block] -> Pres ([Block], SpeakerNotes)
+handleAndFilterNotes blks = do
+  modify $ \st -> st{stSpeakerNotes = mempty}
+  blks' <- walkM handleAndFilterNotes' blks
+  spkNotes <- gets stSpeakerNotes
+  return (blks', spkNotes)
+
 blocksToSlide :: [Block] -> Pres Slide
 blocksToSlide blks = do
+  (blks', spkNotes) <- handleAndFilterNotes blks
   slideLevel <- asks envSlideLevel
-  sld <- blocksToSlide' slideLevel blks
-  spkNotes <- getSpeakerNotes
-  return $ sld{slideSpeakerNotes = spkNotes}
+  blocksToSlide' slideLevel blks' spkNotes
 
 makeNoteEntry :: Int -> [Block] -> [Block]
 makeNoteEntry n blks =
@@ -720,15 +731,14 @@
   anchorSet <- M.keysSet <$> gets stAnchorMap
   if M.null noteIds
     then return []
-    else do let title = case lookupMeta "notes-title" meta of
-                  Just val -> metaValueToInlines val
-                  Nothing  -> [Str "Notes"]
-                ident = Shared.uniqueIdent title anchorSet
-                hdr = Header slideLevel (ident, [], []) title
-            blks <- return $
-                    concatMap (\(n, bs) -> makeNoteEntry n bs) $
+    else let title = case lookupMeta "notes-title" meta of
+                       Just val -> metaValueToInlines val
+                       Nothing  -> [Str "Notes"]
+             ident = Shared.uniqueIdent title anchorSet
+             hdr = Header slideLevel (ident, [], []) title
+             blks = concatMap (\(n, bs) -> makeNoteEntry n bs) $
                     M.toList noteIds
-            return $ hdr : blks
+         in return $ hdr : blks
 
 getMetaSlide :: Pres (Maybe Slide)
 getMetaSlide  = do
@@ -754,7 +764,7 @@
                        , metadataSlideAuthors = authors
                        , metadataSlideDate = date
                        }
-         Nothing
+         mempty
 
 -- adapted from the markdown writer
 elementToListItem :: Shared.Element -> Pres [Block]
@@ -779,8 +789,7 @@
                    Just val -> metaValueToInlines val
                    Nothing  -> [Str "Table of Contents"]
       hdr = Header slideLevel nullAttr tocTitle
-  sld <- blocksToSlide [hdr, contents]
-  return sld
+  blocksToSlide [hdr, contents]
 
 combineParaElems' :: Maybe ParaElem -> [ParaElem] -> [ParaElem]
 combineParaElems' mbPElem [] = maybeToList mbPElem
@@ -803,15 +812,9 @@
   return $ para {paraElems = paraElems'}
 
 applyToShape :: Monad m => (ParaElem -> m ParaElem) -> Shape -> m Shape
-applyToShape f (Pic pPr fp pes) = do
-  pes' <- mapM f pes
-  return $ Pic pPr fp pes'
-applyToShape f (GraphicFrame gfx pes) = do
-  pes' <- mapM f pes
-  return $ GraphicFrame gfx pes'
-applyToShape f (TextBox paras) = do
-  paras' <- mapM (applyToParagraph f) paras
-  return $ TextBox paras'
+applyToShape f (Pic pPr fp pes) = Pic pPr fp <$> mapM f pes
+applyToShape f (GraphicFrame gfx pes) = GraphicFrame gfx <$> mapM f pes
+applyToShape f (TextBox paras) = TextBox <$> mapM (applyToParagraph f) paras
 
 applyToLayout :: Monad m => (ParaElem -> m ParaElem) -> Layout -> m Layout
 applyToLayout f (MetadataSlide title subtitle authors date) = do
@@ -820,9 +823,7 @@
   authors' <- mapM (mapM f) authors
   date' <- mapM f date
   return $ MetadataSlide title' subtitle' authors' date'
-applyToLayout f (TitleSlide title) = do
-  title' <- mapM f title
-  return $ TitleSlide title'
+applyToLayout f (TitleSlide title) = TitleSlide <$> mapM f title
 applyToLayout f (ContentSlide hdr content) = do
   hdr' <- mapM f hdr
   content' <- mapM (applyToShape f) content
@@ -836,11 +837,9 @@
 applyToSlide :: Monad m => (ParaElem -> m ParaElem) -> Slide -> m Slide
 applyToSlide f slide = do
   layout' <- applyToLayout f $ slideLayout slide
-  mbNotes' <- case slideSpeakerNotes slide of
-                Just (SpeakerNotes notes) -> (Just . SpeakerNotes) <$>
-                                             mapM (applyToParagraph f) notes
-                Nothing -> return Nothing
-  return slide{slideLayout = layout', slideSpeakerNotes = mbNotes'}
+  let paras = fromSpeakerNotes $ slideSpeakerNotes slide
+  notes' <- SpeakerNotes <$> mapM (applyToParagraph f) paras
+  return slide{slideLayout = layout', slideSpeakerNotes = notes'}
 
 replaceAnchor :: ParaElem -> Pres ParaElem
 replaceAnchor (Run rProps s)
@@ -886,8 +885,7 @@
     all emptyShape shapes2
 
 emptySlide :: Slide -> Bool
-emptySlide (Slide _ layout Nothing) = emptyLayout layout
-emptySlide _ = False
+emptySlide (Slide _ layout notes) = (notes == mempty) && (emptyLayout layout)
 
 blocksToPresentationSlides :: [Block] -> Pres [Slide]
 blocksToPresentationSlides blks = do
diff --git a/src/Text/Pandoc/Writers/RST.hs b/src/Text/Pandoc/Writers/RST.hs
--- a/src/Text/Pandoc/Writers/RST.hs
+++ b/src/Text/Pandoc/Writers/RST.hs
@@ -31,7 +31,7 @@
 
 reStructuredText:  <http://docutils.sourceforge.net/rst.html>
 -}
-module Text.Pandoc.Writers.RST ( writeRST ) where
+module Text.Pandoc.Writers.RST ( writeRST, flatten ) where
 import Prelude
 import Control.Monad.State.Strict
 import Data.Char (isSpace, toLower)
@@ -263,7 +263,6 @@
           return $ nowrap $ hang 3 ".. " (rub $$ name' $$ cls) $$ blankline
 blockToRST (CodeBlock (_,classes,kvs) str) = do
   opts <- gets stOptions
-  let tabstop = writerTabStop opts
   let startnum = maybe "" (\x -> " " <> text x) $ lookup "startFrom" kvs
   let numberlines = if "numberLines" `elem` classes
                        then "   :number-lines:" <> startnum
@@ -276,11 +275,10 @@
                      c `notElem` ["sourceCode","literate","numberLines"]] of
              []       -> "::"
              (lang:_) -> (".. code:: " <> text lang) $$ numberlines)
-          $+$ nest tabstop (text str) $$ blankline
+          $+$ nest 3 (text str) $$ blankline
 blockToRST (BlockQuote blocks) = do
-  tabstop <- gets $ writerTabStop . stOptions
   contents <- blockListToRST blocks
-  return $ nest tabstop contents <> blankline
+  return $ nest 3 contents <> blankline
 blockToRST (Table caption aligns widths headers rows) = do
   caption' <- inlineListToRST caption
   let blocksToDoc opts bs = do
@@ -338,8 +336,7 @@
 definitionListItemToRST (label, defs) = do
   label' <- inlineListToRST label
   contents <- liftM vcat $ mapM blockListToRST defs
-  tabstop <- gets $ writerTabStop . stOptions
-  return $ nowrap label' $$ nest tabstop (nestle contents <> cr)
+  return $ nowrap label' $$ nest 3 (nestle contents <> cr)
 
 -- | Format a list of lines as line block.
 linesToLineBlock :: PandocMonad m => [[Inline]] -> RST m Doc
@@ -380,8 +377,10 @@
 blockListToRST = blockListToRST' False
 
 transformInlines :: [Inline] -> [Inline]
-transformInlines =  stripLeadingTrailingSpace . insertBS
-                    . filter hasContents . removeSpaceAfterDisplayMath
+transformInlines =  insertBS .
+                    filter hasContents .
+                    removeSpaceAfterDisplayMath .
+                    concatMap (transformNested . flatten)
   where -- empty inlines are not valid RST syntax
         hasContents :: Inline -> Bool
         hasContents (Str "")              = False
@@ -415,6 +414,8 @@
               x : insertBS (y : zs)
         insertBS (x:ys) = x : insertBS ys
         insertBS [] = []
+        transformNested :: [Inline] -> [Inline]
+        transformNested = map (mapNested stripLeadingTrailingSpace)
         surroundComplex :: Inline -> Inline -> Bool
         surroundComplex (Str s@(_:_)) (Str s'@(_:_)) =
           case (last s, head s') of
@@ -451,6 +452,77 @@
         isComplex (Cite _ (x:_))  = isComplex x
         isComplex (Span _ (x:_))  = isComplex x
         isComplex _               = False
+
+-- | Flattens nested inlines. Extracts nested inlines and goes through
+-- them either collapsing them in the outer inline container or
+-- pulling them out of it
+flatten :: Inline -> [Inline]
+flatten outer
+  | null contents = [outer]
+  | otherwise     = combineAll contents
+  where contents = dropInlineParent outer
+        combineAll = foldl combine []
+
+        combine :: [Inline] -> Inline -> [Inline]
+        combine f i = 
+          case (outer, i) of
+          -- quotes are not rendered using RST inlines, so we can keep
+          -- them and they will be readable and parsable
+          (Quoted _ _, _)          -> keep f i
+          (_, Quoted _ _)          -> keep f i
+          -- parent inlines would prevent links from being correctly
+          -- parsed, in this case we prioritise the content over the
+          -- style
+          (_, Link _ _ _)          -> emerge f i
+          -- always give priority to strong text over emphasis
+          (Emph _, Strong _)       -> emerge f i
+          -- drop all other nested styles
+          (_, _)                   -> collapse f i
+
+        emerge f i = f <> [i]
+        keep f i = appendToLast f [i]
+        collapse f i = appendToLast f $ dropInlineParent i
+
+        appendToLast :: [Inline] -> [Inline] -> [Inline]
+        appendToLast [] toAppend = [setInlineChildren outer toAppend]
+        appendToLast flattened toAppend
+          | isOuter lastFlat = init flattened <> [appendTo lastFlat toAppend]
+          | otherwise =  flattened <> [setInlineChildren outer toAppend]
+          where lastFlat = last flattened
+                appendTo o i = mapNested (<> i) o
+                isOuter i = emptyParent i == emptyParent outer
+                emptyParent i = setInlineChildren i []
+
+mapNested :: ([Inline] -> [Inline]) -> Inline -> Inline
+mapNested f i = setInlineChildren i (f (dropInlineParent i))
+
+dropInlineParent :: Inline -> [Inline]
+dropInlineParent (Link _ i _)    = i
+dropInlineParent (Emph i)        = i
+dropInlineParent (Strong i)      = i
+dropInlineParent (Strikeout i)   = i
+dropInlineParent (Superscript i) = i
+dropInlineParent (Subscript i)   = i
+dropInlineParent (SmallCaps i)   = i
+dropInlineParent (Cite _ i)      = i
+dropInlineParent (Image _ i _)   = i
+dropInlineParent (Span _ i)      = i
+dropInlineParent (Quoted _ i)    = i
+dropInlineParent i               = [i] -- not a parent, like Str or Space
+
+setInlineChildren :: Inline -> [Inline] -> Inline
+setInlineChildren (Link a _ t) i    = Link a i t
+setInlineChildren (Emph _) i        = Emph i
+setInlineChildren (Strong _) i      = Strong i
+setInlineChildren (Strikeout _) i   = Strikeout i
+setInlineChildren (Superscript _) i = Superscript i
+setInlineChildren (Subscript _) i   = Subscript i
+setInlineChildren (SmallCaps _) i   = SmallCaps i
+setInlineChildren (Quoted q _) i    = Quoted q i
+setInlineChildren (Cite c _) i      = Cite c i
+setInlineChildren (Image a _ t) i   = Image a i t
+setInlineChildren (Span a _) i      = Span a i
+setInlineChildren leaf _            = leaf
 
 inlineListToRST :: PandocMonad m => [Inline] -> RST m Doc
 inlineListToRST = writeInlines . walk transformInlines
diff --git a/stack.yaml b/stack.yaml
--- a/stack.yaml
+++ b/stack.yaml
@@ -12,12 +12,16 @@
 packages:
 - '.'
 extra-deps:
-- pandoc-citeproc-0.14.2
+- pandoc-citeproc-0.14.3.1
 - skylighting-0.7.0.2
 - skylighting-core-0.7.0.2
 - ansi-terminal-0.8.0.2
 - tasty-1.0.1.1
+- test-framework-0.8.2.0
 - pandoc-types-1.17.4.2
+- cmark-gfm-0.1.3
+- hslua-module-text-0.1.2.1
+- texmath-0.10.1.2
 ghc-options:
    "$locals": -fhide-source-paths -XNoImplicitPrelude
 resolver: lts-10.10
diff --git a/test/Tests/Old.hs b/test/Tests/Old.hs
--- a/test/Tests/Old.hs
+++ b/test/Tests/Old.hs
@@ -59,7 +59,7 @@
           ]
         , testGroup "s5"
           [ s5WriterTest "basic" ["-s"] "s5"
-          , s5WriterTest "fancy" ["-s","-m","-i"] "s5"
+          , s5WriterTest "fancy" ["-s","--mathjax","-i"] "s5"
           , s5WriterTest "fragment" [] "html4"
           , s5WriterTest "inserts"  ["-s", "-H", "insert",
             "-B", "insert", "-A", "insert", "-c", "main.css"] "html4"
@@ -95,6 +95,7 @@
           , fb2WriterTest "images" [] "fb2/images.markdown" "fb2/images.fb2"
           , fb2WriterTest "images-embedded" [] "fb2/images-embedded.html" "fb2/images-embedded.fb2"
           , fb2WriterTest "math" [] "fb2/math.markdown" "fb2/math.fb2"
+          , fb2WriterTest "meta" [] "fb2/meta.markdown" "fb2/meta.fb2"
           , fb2WriterTest "tables" [] "tables.native" "tables.fb2"
           , fb2WriterTest "testsuite" [] "testsuite.native" "writer.fb2"
           ]
diff --git a/test/Tests/Readers/Docx.hs b/test/Tests/Readers/Docx.hs
--- a/test/Tests/Readers/Docx.hs
+++ b/test/Tests/Readers/Docx.hs
@@ -291,6 +291,10 @@
             "docx/codeblock.docx"
             "docx/codeblock.native"
           , testCompare
+            "combine adjacent code blocks"
+            "docx/adjacent_codeblocks.docx"
+            "docx/adjacent_codeblocks.native"
+          , testCompare
             "dropcap paragraphs"
             "docx/drop_cap.docx"
             "docx/drop_cap.native"
diff --git a/test/Tests/Readers/FB2.hs b/test/Tests/Readers/FB2.hs
new file mode 100644
--- /dev/null
+++ b/test/Tests/Readers/FB2.hs
@@ -0,0 +1,29 @@
+{-# LANGUAGE NoImplicitPrelude #-}
+
+module Tests.Readers.FB2 (tests) where
+
+import Prelude
+import Test.Tasty
+import Tests.Helpers
+import Test.Tasty.Golden (goldenVsString)
+import qualified Data.ByteString as BS
+import Text.Pandoc
+import Text.Pandoc.UTF8 (toText, fromTextLazy)
+import Data.Text (Text)
+import Data.Text.Lazy (fromStrict)
+import System.FilePath (replaceExtension)
+
+fb2ToNative :: Text -> Text
+fb2ToNative = purely (writeNative def{ writerTemplate = Just "" }) . purely (readFB2 def)
+
+fb2Test :: TestName -> FilePath -> TestTree
+fb2Test name path = goldenVsString name native (fromTextLazy . fromStrict . fb2ToNative . toText <$> BS.readFile path)
+  where native = replaceExtension path ".native"
+
+tests :: [TestTree]
+tests = [ fb2Test "Emphasis" "fb2/reader/emphasis.fb2"
+        , fb2Test "Titles" "fb2/reader/titles.fb2"
+        , fb2Test "Epigraph" "fb2/reader/epigraph.fb2"
+        , fb2Test "Poem" "fb2/reader/poem.fb2"
+        , fb2Test "Meta" "fb2/reader/meta.fb2"
+        ]
diff --git a/test/Tests/Readers/Markdown.hs b/test/Tests/Readers/Markdown.hs
--- a/test/Tests/Readers/Markdown.hs
+++ b/test/Tests/Readers/Markdown.hs
@@ -295,6 +295,9 @@
           , test markdownSmart "apostrophe after math" $ -- issue #1909
               "The value of the $x$'s and the systems' condition." =?>
               para (text "The value of the " <> math "x" <> text "\8217s and the systems\8217 condition.")
+          , test markdownSmart "unclosed double quote"
+            ("**this should \"be bold**"
+            =?> para (strong "this should \"be bold"))
           ]
         , testGroup "footnotes"
           [ "indent followed by newline and flush-left text" =:
diff --git a/test/Tests/Readers/Muse.hs b/test/Tests/Readers/Muse.hs
--- a/test/Tests/Readers/Muse.hs
+++ b/test/Tests/Readers/Muse.hs
@@ -167,6 +167,8 @@
 
       , "Code tag" =: "<code>foo(bar)</code>" =?> para (code "foo(bar)")
 
+      , "Math tag" =: "<math>\\sum_{i=0}^n i^2</math>" =?> para (math "\\sum_{i=0}^n i^2")
+
       , "Verbatim tag" =: "*<verbatim>*</verbatim>*" =?> para (emph "*")
 
       , "Verbatim inside code" =: "<code><verbatim>foo</verbatim></code>" =?> para (code "<verbatim>foo</verbatim>")
@@ -186,6 +188,9 @@
         , "Link with description" =:
           "[[https://amusewiki.org/][A Muse Wiki]]" =?>
           para (link "https://amusewiki.org/" "" (text "A Muse Wiki"))
+        , "Link with empty description" =:
+          "[[https://amusewiki.org/][]]" =?>
+          para (link "https://amusewiki.org/" "" (text ""))
         , "Image" =:
           "[[image.jpg]]" =?>
           para (image "image.jpg" "" mempty)
@@ -204,19 +209,25 @@
         -- This test also makes sure '=' without whitespace is not treated as code markup
         , "No implicit links" =: "http://example.org/index.php?action=view&id=1"
                =?> para "http://example.org/index.php?action=view&id=1"
+        , "Link with empty URL" =: "[[][empty URL]]" =?> para (link "" "" (text "empty URL"))
+        , "No footnotes inside links" =:
+          "[[https://amusewiki.org/][foo[1]]" =?>
+          para (link "https://amusewiki.org/" "" (text "foo[1"))
         ]
 
       , testGroup "Literal"
         [ test emacsMuse "Inline literal"
           ("Foo<literal style=\"html\">lit</literal>bar" =?>
           para (text "Foo" <> rawInline "html" "lit" <> text "bar"))
+        , test emacsMuse "Single inline literal in paragraph"
+          ("<literal style=\"html\">lit</literal>" =?>
+          para (rawInline "html" "lit"))
         ]
       ]
 
   , testGroup "Blocks" $
-      [ -- round-trip commented out for now, because it fails too often:
-        testProperty "Round trip" roundTrip | False ] ++
-      [  "Block elements end paragraphs" =:
+      [ testProperty "Round trip" roundTrip
+      , "Block elements end paragraphs" =:
         T.unlines [ "First paragraph"
                   , "----"
                   , "Second paragraph"
@@ -274,6 +285,23 @@
                       ] =?>
             divWith ("foo", [], []) (para "Foo bar")
           ]
+        , "Biblio" =:
+          T.unlines [ "<biblio>"
+                    , ""
+                    , "Author, *Title*, description"
+                    , ""
+                    , "Another author, *Another title*, another description"
+                    , ""
+                    , "</biblio>"
+                    ] =?>
+          divWith ("", ["biblio"], []) (para (text "Author, " <> emph "Title" <> ", description") <>
+                                        para (text "Another author, " <> emph "Another title" <> text ", another description"))
+        , "Play" =:
+          T.unlines [ "<play>"
+                    , "Foo bar"
+                    , "</play>"
+                    ] =?>
+          divWith ("", ["play"], []) (para "Foo bar")
         , "Verse" =:
           T.unlines [ "> This is"
                     , "> First stanza"
@@ -497,6 +525,7 @@
         , "Text after empty comment" =: ";\nfoo" =?> para "foo" -- Make sure we don't consume newline while looking for whitespace
         , "Not a comment (does not start with a semicolon)" =: " ; Not a comment" =?> para (text "; Not a comment")
         , "Not a comment (has no space after semicolon)" =: ";Not a comment" =?> para (text ";Not a comment")
+        , "Not a comment (semicolon not in the first column)" =: " - ; foo" =?> bulletList [para "; foo"]
         ]
       , testGroup "Headers"
         [ "Part" =:
@@ -528,23 +557,38 @@
                     ] =?>
           blockQuote (para "* Hi")
         , "Headers consume anchors" =:
-          T.unlines [ "** Foo"
+          T.unlines [ "; A comment to make sure anchor is not parsed as a directive"
                     , "#bar"
+                    , "** Foo"
                     ] =?>
           headerWith ("bar",[],[]) 2 "Foo"
         , "Headers don't consume anchors separated with a blankline" =:
-          T.unlines [ "** Foo"
-                    , ""
+          T.unlines [ "; A comment to make sure anchor is not parsed as a directive"
                     , "#bar"
+                    , ""
+                    , "** Foo"
                     ] =?>
-          header 2 "Foo" <>
-          para (spanWith ("bar", [], []) mempty)
+          para (spanWith ("bar", [], []) mempty) <>
+          header 2 "Foo"
+        , "Headers terminate paragraph" =:
+          T.unlines [ "foo"
+                    , "* bar"
+                    ] =?>
+          para "foo" <> header 1 "bar"
         , "Headers terminate lists" =:
           T.unlines [ " - foo"
                     , "* bar"
                     ] =?>
           bulletList [ para "foo" ] <>
           header 1 "bar"
+        , test emacsMuse "Paragraphs terminate Emacs Muse headers"
+          (T.unlines [ "* Foo"
+                    , "bar"
+                    ] =?> header 1 "Foo" <> para "bar")
+        , "Paragraphs don't terminate Text::Amuse headers" =:
+          T.unlines [ "* Foo"
+                    , "bar"
+                    ] =?> header 1 "Foo\nbar"
         ]
       , testGroup "Directives"
         [ "Title" =:
@@ -593,6 +637,11 @@
                     , "#anchor and ends here."
                     ] =?>
           para ("Paragraph starts here\n" <> spanWith ("anchor", [], []) mempty <> "and ends here.")
+        , "Anchor with \"-\"" =:
+          T.unlines [ "; A comment to make sure anchor is not parsed as a directive"
+                    , "#anchor-id Target"
+                    ] =?>
+          para (spanWith ("anchor-id", [], []) mempty <> "Target")
         ]
       , testGroup "Footnotes"
         [ "Simple footnote" =:
@@ -610,6 +659,15 @@
                     ] =?>
           para (text "Start recursion here" <>
                 note (para "Recursion continues here[1]"))
+        , "Nested footnotes" =:
+          T.unlines [ "Footnote: [1]"
+                    , ""
+                    , "[1] Nested: [2]"
+                    , ""
+                    , "[2] No recursion: [1]"
+                    ] =?>
+          para (text "Footnote: " <>
+                note (para (text "Nested: " <> note (para $ text "No recursion: [1]"))))
         , "No zero footnotes" =:
           T.unlines [ "Here is a footnote[0]."
                     , ""
@@ -1109,6 +1167,24 @@
         definitionList [ ("First term", [ para "Definition of first term\nand its continuation." ])
                        , ("Second term", [ para "Definition of second term." ])
                        ]
+      , "Definition list with verse" =:
+        T.unlines
+          [ " First term :: Definition of first term"
+          , "  > First verse"
+          , "  > Second line of first verse"
+          , ""
+          , "               > Second verse"
+          , "               > Second line of second verse"
+          ] =?>
+        definitionList [ ("First term", [ para "Definition of first term" <>
+                                          lineBlock [ text "First verse"
+                                                    , text "Second line of first verse"
+                                                    ] <>
+                                          lineBlock [ text "Second verse"
+                                                    , text "Second line of second verse"
+                                                    ]
+                                        ])
+                       ]
       , test emacsMuse "Multi-line definition lists from Emacs Muse manual"
         (T.unlines
           [ "Term1 ::"
@@ -1221,7 +1297,7 @@
           , " - <quote>"
           , "   foo"
           , "   </quote>"
-          , " bar" -- Do not consume whitespace while looking for arbitraritly indented </quote>
+          , " bar" -- Do not consume whitespace while looking for arbitrarily indented </quote>
           , "</quote>"
           ] =?>
         blockQuote (bulletList [ blockQuote $ para "foo" ] <> para "bar")
diff --git a/test/Tests/Writers/FB2.hs b/test/Tests/Writers/FB2.hs
--- a/test/Tests/Writers/FB2.hs
+++ b/test/Tests/Writers/FB2.hs
@@ -25,8 +25,8 @@
           ]
         , testGroup "inlines"
           [
-            "Emphasis"      =:  emph "emphasized"
-                            =?> fb2 "<emphasis>emphasized</emphasis>"
+            "Emphasis"      =:  para (emph "emphasized")
+                            =?> fb2 "<p><emphasis>emphasized</emphasis></p>"
           ]
         , "bullet list" =: bulletList [ plain $ text "first"
                                       , plain $ text "second"
diff --git a/test/Tests/Writers/Muse.hs b/test/Tests/Writers/Muse.hs
--- a/test/Tests/Writers/Muse.hs
+++ b/test/Tests/Writers/Muse.hs
@@ -10,7 +10,7 @@
 import Text.Pandoc.Builder
 
 muse :: (ToPandoc a) => a -> String
-muse = museWithOpts def{ writerWrapText = WrapNone,
+muse = museWithOpts def{ writerWrapText = WrapPreserve,
                          writerExtensions = extensionsFromList [Ext_amuse,
                                                                 Ext_auto_identifiers] }
 
@@ -74,8 +74,8 @@
                    , plain $ text "second"
                    , plain $ text "third"
                    ]
-                =?> unlines [ " I.   first"
-                            , " II.  second"
+                =?> unlines [ " I. first"
+                            , " II. second"
                             , " III. third"
                             ]
               , "bullet list" =: bulletList [ plain $ text "first"
@@ -112,6 +112,24 @@
                             , " <verbatim></verbatim> :: second description"
                             , " <verbatim></verbatim> :: third description"
                             ]
+              , "definition list terms starting with space" =:
+                definitionList [ (text "first definition", [plain $ text "first description"])
+                               , (space <> str "foo", [plain $ text "second description"])
+                               , (str " > bar", [plain $ text "third description"])
+                               ]
+                =?> unlines [ " first definition :: first description"
+                            , " <verbatim></verbatim> foo :: second description"
+                            , " <verbatim></verbatim> > bar :: third description"
+                            ]
+              , "definition list terms starting with list markers" =:
+                definitionList [ (text "first definition", [plain $ text "first description"])
+                               , (str "-", [plain $ text "second description"])
+                               , (str "1.", [plain $ text "third description"])
+                               ]
+                =?> unlines [ " first definition :: first description"
+                            , " <verbatim></verbatim>- :: second description"
+                            , " <verbatim></verbatim>1. :: third description"
+                            ]
               ]
             -- Test that lists of the same type and style are separated with two blanklines
             , testGroup "sequential lists"
@@ -138,11 +156,11 @@
                 orderedListWith (1, UpperRoman, DefaultDelim) [ para $ text "Third"
                                                               , para $ text "Fourth"
                                                               ] =?>
-                unlines [ " I.  First"
+                unlines [ " I. First"
                         , " II. Second"
                         , ""
                         , ""
-                        , " I.  Third"
+                        , " I. Third"
                         , " II. Fourth"
                         ]
               , "ordered lists with equal styles" =:
@@ -169,7 +187,7 @@
                 unlines [ " - First"
                         , " - Second"
                         , ""
-                        , " I.  Third"
+                        , " I. Third"
                         , " II. Fourth"
                         ]
               , "different style ordered lists" =:
@@ -179,7 +197,7 @@
                 orderedListWith (1, Decimal, DefaultDelim) [ para $ text "Third"
                                                            , para $ text "Fourth"
                                                            ] =?>
-                unlines [ " I.  First"
+                unlines [ " I. First"
                         , " II. Second"
                         , ""
                         , " 1. Third"
@@ -254,18 +272,23 @@
                       ]
             , "heading with ID" =:
                headerWith ("bar", [], []) 2 (text "Foo") =?>
-               unlines [ "** Foo"
-                       , "#bar"
+               unlines [ "#bar"
+                       , "** Foo"
                       ]
+            , "empty heading" =: header 4 (mempty) =?> "**** <verbatim></verbatim>"
             ]
           , "horizontal rule" =: horizontalRule =?> "----"
-          , "escape horizontal rule" =: para (text "----") =?> "<verbatim>----</verbatim>"
+          , "escape horizontal rule" =: para (text "----") =?> "<verbatim></verbatim>----"
+          , "escape long horizontal rule" =: para (text "----------") =?> "<verbatim></verbatim>----------"
+          , "don't escape horizontal inside paragraph" =: para (text "foo ---- bar") =?> "foo ---- bar"
           , "escape nonbreaking space" =: para (text "~~") =?> "<verbatim>~~</verbatim>"
+          , "escape > in the beginning of line" =: para (text "> foo bar") =?> "<verbatim></verbatim>> foo bar"
           , testGroup "tables"
             [ "table without header" =:
               let rows = [[para $ text "Para 1.1", para $ text "Para 1.2"]
                          ,[para $ text "Para 2.1", para $ text "Para 2.2"]]
-              in simpleTable [] rows
+              in table mempty [(AlignDefault,0.0),(AlignDefault,0.0)]
+                       [mempty, mempty] rows
               =?>
               unlines [ " Para 1.1 | Para 1.2"
                       , " Para 2.1 | Para 2.2"
@@ -285,7 +308,8 @@
                   headers = [plain $ text "header 1", plain $ text "header 2"]
                   rows = [[para $ text "Para 1.1", para $ text "Para 1.2"]
                          ,[para $ text "Para 2.1", para $ text "Para 2.2"]]
-              in table caption mempty headers rows
+              in table caption [(AlignDefault,0.0),(AlignDefault,0.0)]
+                        headers rows
               =?> unlines [ " header 1 || header 2"
                           , " Para 1.1 |  Para 1.2"
                           , " Para 2.1 |  Para 2.2"
@@ -301,8 +325,11 @@
           [ testGroup "string"
             [ "string" =: str "foo" =?> "foo"
             , "escape footnote" =: str "[1]" =?> "<verbatim>[1]</verbatim>"
+            , "do not escape brackets" =: str "[12ab]" =?> "[12ab]"
             , "escape verbatim close tag" =: str "foo</verbatim>bar"
                =?> "<verbatim>foo<</verbatim><verbatim>/verbatim>bar</verbatim>"
+            , "escape link-like text" =: str "[[https://www.example.org]]"
+               =?> "<verbatim>[[https://www.example.org]]</verbatim>"
             , "escape pipe to avoid accidental tables" =: str "foo | bar"
                =?> "<verbatim>foo | bar</verbatim>"
             , "escape hash to avoid accidental anchors" =: text "#foo bar"
@@ -312,15 +339,19 @@
             -- We don't want colons to be escaped if they can't be confused
             -- with definition list item markers.
             , "do not escape colon" =: str ":" =?> ":"
-            , "escape - to avoid accidental unordered lists" =: text " - foo" =?> " <verbatim>-</verbatim> foo"
+            , "escape - to avoid accidental unordered lists" =: text " - foo" =?> "<verbatim></verbatim> - foo"
             , "escape - inside a list to avoid accidental nested unordered lists" =:
               bulletList [ (para $ text "foo") <>
                            (para $ text "- bar")
                          ] =?>
               unlines [ " - foo"
                       , ""
-                      , "   <verbatim>-</verbatim> bar"
+                      , "   <verbatim></verbatim>- bar"
                       ]
+            , "escape ; to avoid accidental comments" =: text "; foo" =?> "<verbatim></verbatim>; foo"
+            , "escape ; after softbreak" =: text "foo" <> softbreak <> text "; bar" =?> "foo\n<verbatim></verbatim>; bar"
+            , "escape ; after linebreak" =: text "foo" <> linebreak <> text "; bar" =?> "foo<br>\n<verbatim></verbatim>; bar"
+            , "do not escape ; inside paragraph" =: text "foo ; bar" =?> "foo ; bar"
             ]
           , testGroup "emphasis"
             [ "emph" =: emph (text "foo") =?> "<em>foo</em>"
@@ -343,11 +374,13 @@
             ]
           , testGroup "spaces"
             [ "space" =: text "a" <> space <> text "b" =?> "a b"
-            , "soft break" =: text "a" <> softbreak <> text "b" =?> "a b"
-            , test (museWithOpts def{ writerWrapText = WrapPreserve })
-                   "preserve soft break" $ text "a" <> softbreak <> text "b"
-                   =?> "a\nb"
+            , "soft break" =: text "a" <> softbreak <> text "b" =?> "a\nb"
+            , test (museWithOpts def{ writerWrapText = WrapNone })
+                   "remove soft break" $ text "a" <> softbreak <> text "b"
+                   =?> "a b"
             , "line break" =: text "a" <> linebreak <> text "b" =?> "a<br>\nb"
+            , "no newline after line break in header" =: header 1 (text "a" <> linebreak <> text "b") =?> "* a<br>b"
+            , "no softbreak in header" =: header 1 (text "a" <> softbreak <> text "b") =?> "* a b"
             ]
           , testGroup "math"
             [ "inline math" =: math "2^3" =?> "2<sup>3</sup>"
@@ -372,22 +405,47 @@
                                                =?> "[[URL:1.png][Link to image]]"
             , "link to image without description" =: link "1.png" "" (str "1.png")
                                                   =?> "[[URL:1.png]]"
+
+            , testGroup "escape brackets in links"
+              [ "link with description"
+                =: link "https://example.com/foo].txt" "" (str "Description")
+                =?> "[[https://example.com/foo%5D.txt][Description]]"
+              , "link without description"
+                =: link "https://example.com/foo].txt" "" (str "https://example.com/foo].txt")
+                =?> "[[https://example.com/foo%5D.txt][<verbatim>https://example.com/foo].txt</verbatim>]]"
+              , "image link with description"
+                =: link "foo]bar.png" "" (str "Image link")
+                =?> "[[URL:foo%5Dbar.png][Image link]]"
+              , "image link without description"
+                =: link "foo]bar.png" "" (str "foo]bar.png")
+                =?> "[[URL:foo%5Dbar.png][<verbatim>foo]bar.png</verbatim>]]"
+              ]
             ]
           , "image" =: image "image.png" "Image 1" (str "") =?> "[[image.png][Image 1]]"
           , "image with width" =:
             imageWith ("", [], [("width", "60%")]) "image.png" "Image" (str "") =?>
             "[[image.png 60][Image]]"
+          , "escape brackets in image title" =: image "image.png" "Foo]bar" (str "") =?> "[[image.png][<verbatim>Foo]bar</verbatim>]]"
           , "note" =: note (plain (text "Foo"))
                    =?> unlines [ "[1]"
                                , ""
                                , "[1] Foo"
                                ]
           , "span with class" =: spanWith ("",["foobar"],[]) (text "Some text")
-                   =?> "<class name=\"foobar\">Some text</class>"
-          , "span with anchor" =: spanWith ("anchor", [], []) (text "Foo bar")
+                              =?> "<class name=\"foobar\">Some text</class>"
+          , "span without class" =: spanWith ("",[],[]) (text "Some text")
+                                 =?> "<class>Some text</class>"
+          , "span with anchor" =: spanWith ("anchor", [], []) (mempty) <> (text "Foo bar")
                                =?> "#anchor Foo bar"
+          , "empty span with anchor" =: spanWith ("anchor", [], []) (mempty)
+                                     =?> "#anchor"
+          , "empty span without class and anchor" =: spanWith ("", [], []) (mempty)
+                                                  =?> "<class></class>"
           , "span with class and anchor" =: spanWith ("anchor", ["foo"], []) (text "bar")
                                          =?> "#anchor <class name=\"foo\">bar</class>"
+          , "adjacent spans" =: spanWith ("", ["syllable"], []) (str "wa") <>
+                                spanWith ("", ["syllable"], []) (str "ter")
+                             =?> "<class name=\"syllable\">wa</class><class name=\"syllable\">ter</class>"
           , testGroup "combined"
             [ "emph word before" =:
                 para (text "foo" <> emph (text "bar")) =?>
diff --git a/test/Tests/Writers/Powerpoint.hs b/test/Tests/Writers/Powerpoint.hs
--- a/test/Tests/Writers/Powerpoint.hs
+++ b/test/Tests/Writers/Powerpoint.hs
@@ -87,6 +87,10 @@
                          def
                          "pptx/speaker_notes.native"
                          "pptx/speaker_notes.pptx"
+                       , pptxTests "speaker notes after a separating block"
+                         def
+                         "pptx/speaker_notes_afterseps.native"
+                         "pptx/speaker_notes_afterseps.pptx"
                        , pptxTests "remove empty slides"
                          def
                          "pptx/remove_empty_slides.native"
diff --git a/test/Tests/Writers/RST.hs b/test/Tests/Writers/RST.hs
--- a/test/Tests/Writers/RST.hs
+++ b/test/Tests/Writers/RST.hs
@@ -4,10 +4,12 @@
 
 import Prelude
 import Test.Tasty
+import Test.Tasty.HUnit
 import Tests.Helpers
 import Text.Pandoc
 import Text.Pandoc.Arbitrary ()
 import Text.Pandoc.Builder
+import Text.Pandoc.Writers.RST
 
 infix 4 =:
 (=:) :: (ToString a, ToPandoc a)
@@ -24,23 +26,23 @@
                                             para $ text "baz"])] =?>
               unlines
               [ "foo"
-              , "    .. rubric:: bar"
+              , "   .. rubric:: bar"
               , ""
-              , "    baz"]
+              , "   baz"]
           , "in block quote" =:
               blockQuote (header 1 (text "bar")) =?>
-              "    .. rubric:: bar"
+              "   .. rubric:: bar"
           , "with id" =:
               blockQuote (headerWith ("foo",[],[]) 1 (text "bar")) =?>
               unlines
-              [ "    .. rubric:: bar"
-              , "       :name: foo"]
+              [ "   .. rubric:: bar"
+              , "      :name: foo"]
           , "with id class" =:
               blockQuote (headerWith ("foo",["baz"],[]) 1 (text "bar")) =?>
               unlines
-              [ "    .. rubric:: bar"
-              , "       :name: foo"
-              , "       :class: baz"]
+              [ "   .. rubric:: bar"
+              , "      :name: foo"
+              , "      :class: baz"]
           ]
         , testGroup "ligatures" -- handling specific sequences of blocks
           [ "a list is closed by a comment before a quote" =: -- issue 4248
@@ -50,8 +52,22 @@
               , ""
               , ".."
               , ""
-              , "    quoted"]
+              , "   quoted"]
           ]
+        , testGroup "flatten"
+          [ testCase "emerges nested styles as expected" $
+            flatten (Emph [Str "1", Strong [Str "2"], Str "3"]) @?=
+            [Emph [Str "1"], Strong [Str "2"], Emph [Str "3"]]
+          , testCase "could introduce trailing spaces" $
+            flatten (Emph [Str "f", Space, Strong [Str "2"]]) @?=
+            [Emph [Str "f", Space], Strong [Str "2"]]
+            -- the test above is the reason why we call
+            -- stripLeadingTrailingSpace through transformNested after
+            -- flatten
+          , testCase "preserves empty parents" $
+            flatten (Image ("",[],[]) [] ("loc","title")) @?=
+            [Image ("",[],[]) [] ("loc","title")]
+          ]
         , testGroup "inlines"
           [ "are removed when empty" =: -- #4434
             plain (strong (str "")) =?> ""
@@ -64,6 +80,17 @@
             strong (space <> str "text" <> space <> space) =?> "**text**"
           , "single space stripped" =:
             strong space =?> ""
+          , "give priority to strong style over emphasis" =:
+            strong (emph (strong (str "s"))) =?> "**s**"
+          , "links are not elided by outer style" =:
+            strong (emph (link "loc" "" (str "text"))) =?>
+            "`text <loc>`__"
+          , "RST inlines cannot start nor end with spaces" =:
+            emph (str "f" <> space <> strong (str "d") <> space <> str "l") =?>
+            "*f*\\ **d**\\ *l*"
+          , "keeps quotes" =:
+            strong (str "f" <> doubleQuoted (str "d") <> str "l") =?>
+            "**f“d”l**"
           ]
         , testGroup "headings"
           [ "normal heading" =:
diff --git a/test/command/2649.md b/test/command/2649.md
--- a/test/command/2649.md
+++ b/test/command/2649.md
@@ -67,7 +67,8 @@
 ! Aantal
 |-
 | 1
-|align=left| {{FR-VLAG}} [[Sébastien Loeb]] | 78
+|align=left| {{FR-VLAG}} [[Sébastien Loeb]]
+| 78
 |-
 | 2
 |align=left| {{FR-VLAG}} '''[[Sébastien Ogier]]'''
@@ -79,24 +80,25 @@
 |}
 ^D
 <table>
+<thead>
+<tr class="header">
+<th><p>Plaats</p></th>
+<th><p>Rijder</p></th>
+<th><p>Aantal</p></th>
+</tr>
+</thead>
 <tbody>
 <tr class="odd">
-<td></td>
-<td><p>Plaats</p></td>
-<td><p>Rijder</p></td>
-<td><p>Aantal</p></td>
-</tr>
-<tr class="even">
 <td><p>1</p></td>
 <td><p><a href="Sébastien_Loeb" title="wikilink">Sébastien Loeb</a></p></td>
 <td><p>78</p></td>
 </tr>
-<tr class="odd">
+<tr class="even">
 <td><p>2</p></td>
 <td><p><strong><a href="Sébastien_Ogier" title="wikilink">Sébastien Ogier</a></strong></p></td>
 <td><p>38</p></td>
 </tr>
-<tr class="even">
+<tr class="odd">
 <td><p>10</p></td>
 <td><p><a href="Hannu_Mikkola" title="wikilink">Hannu Mikkola</a></p></td>
 <td><p>18</p></td>
diff --git a/test/command/3348.md b/test/command/3348.md
--- a/test/command/3348.md
+++ b/test/command/3348.md
@@ -7,7 +7,7 @@
         line of text
   ----- ------------------------------------------------
 ^D
-[Table [] [AlignRight,AlignLeft] [8.333333333333333e-2,0.6666666666666666]
+[Table [] [AlignRight,AlignLeft] [8.333333333333333e-2,0.6805555555555556]
  [[]
  ,[]]
  [[[Plain [Str "foo"]]
diff --git a/test/command/3675.md b/test/command/3675.md
--- a/test/command/3675.md
+++ b/test/command/3675.md
@@ -7,9 +7,9 @@
 ^D
 .. code:: python
 
-    print("hello")
+   print("hello")
 
 ..
 
-    block quote
+   block quote
 ````
diff --git a/test/command/4320.md b/test/command/4320.md
--- a/test/command/4320.md
+++ b/test/command/4320.md
@@ -7,9 +7,9 @@
   ,[BlockQuote
     [Para [Strong [Str "thisIsGoingToBeTooLongAnyway"]]]]]]]
 ^D
-+-------+--------------------------------------+
-| one   | two                                  |
-+=======+======================================+
-| ports |     **thisIsGoingToBeTooLongAnyway** |
-+-------+--------------------------------------+
++-------+-------------------------------------+
+| one   | two                                 |
++=======+=====================================+
+| ports |    **thisIsGoingToBeTooLongAnyway** |
++-------+-------------------------------------+
 ```
diff --git a/test/command/4513.md b/test/command/4513.md
new file mode 100644
--- /dev/null
+++ b/test/command/4513.md
@@ -0,0 +1,9 @@
+```
+% pandoc -f textile -t native
+|_. heading 1 |_. heading 2|
+^D
+[Table [] [AlignDefault,AlignDefault] [0.0,0.0]
+ [[Plain [Str "heading",Space,Str "1"]]
+ ,[Plain [Str "heading",Space,Str "2"]]]
+ []]
+```
diff --git a/test/command/4527.md b/test/command/4527.md
new file mode 100644
--- /dev/null
+++ b/test/command/4527.md
@@ -0,0 +1,21 @@
+# Raw TeX blocks in CommonMark with and without raw_tex
+
+```
+% pandoc -f latex -t commonmark-raw_tex
+\someunknowncommand
+
+Hello.
+^D
+Hello.
+```
+
+```
+% pandoc -f latex -t commonmark+raw_tex
+\someunknowncommand
+
+Hello.
+^D
+\someunknowncommand
+
+Hello.
+```
diff --git a/test/command/4529.md b/test/command/4529.md
new file mode 100644
--- /dev/null
+++ b/test/command/4529.md
@@ -0,0 +1,36 @@
+```
+% pandoc -f latex -t plain
+\chapter{First chapter}\label{sec:chp1}
+The next chapter is Chapter~\ref{sec:chp2}.
+\section{First section}\label{sec:chp1sec1}
+The next section is Section~\ref{sec:chp2sec1}.
+
+\chapter{Second chapter}\label{sec:chp2}
+The previous chapter is Chapter~\ref{sec:chp1}.
+\section{First section}\label{sec:chp2sec1}
+The previous section is Section~\ref{sec:chp1sec1}.
+^D
+
+
+FIRST CHAPTER
+
+
+The next chapter is Chapter 2.
+
+
+First section
+
+The next section is Section 2.1.
+
+
+
+SECOND CHAPTER
+
+
+The previous chapter is Chapter 1.
+
+
+First section
+
+The previous section is Section 1.1.
+```
diff --git a/test/command/4550.md b/test/command/4550.md
new file mode 100644
--- /dev/null
+++ b/test/command/4550.md
@@ -0,0 +1,7 @@
+```
+% pandoc -f markdown-smart -t ms
+A ‘simple’ example
+^D
+.LP
+A ‘simple’ example
+```
diff --git a/test/command/4578.md b/test/command/4578.md
new file mode 100644
--- /dev/null
+++ b/test/command/4578.md
@@ -0,0 +1,14 @@
+```
+% pandoc -t markdown
+  ------ ------- --------------- ---------------------
+  One    row                12.0 Example of a row that
+                                 spans multiple lines.
+
+  ------ ------- --------------- ---------------------
+^D
+  ------ ------- --------------- ---------------------
+  One    row                12.0 Example of a row that
+                                 spans multiple lines.
+
+  ------ ------- --------------- ---------------------
+```
diff --git a/test/command/4579.md b/test/command/4579.md
new file mode 100644
--- /dev/null
+++ b/test/command/4579.md
@@ -0,0 +1,16 @@
+```
+% pandoc -f rst -t native
+.. list-table::
+  :header-rows: 1
+
+  * - Foo
+    - Bar
+  * - spam
+    - ham
+^D
+[Table [] [AlignDefault,AlignDefault] [0.0,0.0]
+ [[Plain [Str "Foo"]]
+ ,[Plain [Str "Bar"]]]
+ [[[Plain [Str "spam"]]
+  ,[Plain [Str "ham"]]]]]
+```
diff --git a/test/command/4589.md b/test/command/4589.md
new file mode 100644
--- /dev/null
+++ b/test/command/4589.md
@@ -0,0 +1,14 @@
+```
+% pandoc -f markdown -t latex
+\newcommand{\one}[1]{#1}
+\newcommand{\two}[1]{#1}
+
+Formatting *is* working **here**. But sticking \one{two }\two{commands}
+together *breaks* formatting.
+^D
+\newcommand{\one}[1]{#1}
+\newcommand{\two}[1]{#1}
+
+Formatting \emph{is} working \textbf{here}. But sticking two commands
+together \emph{breaks} formatting.
+```
diff --git a/test/command/4594.md b/test/command/4594.md
new file mode 100644
--- /dev/null
+++ b/test/command/4594.md
@@ -0,0 +1,24 @@
+```
+% pandoc -f markdown -t latex
+Some **bold** text here.
+
+\begin{figure}[htbp]
+\centering
+\def\svgwidth{\columnwidth}
+\import{img/}{vectors.pdf_tex}
+\caption{Some caption.}
+\end{figure}
+
+Some *italic* text here.
+^D
+Some \textbf{bold} text here.
+
+\begin{figure}[htbp]
+\centering
+\def\svgwidth{\columnwidth}
+\import{img/}{vectors.pdf_tex}
+\caption{Some caption.}
+\end{figure}
+
+Some \emph{italic} text here.
+```
diff --git a/test/command/4598.md b/test/command/4598.md
new file mode 100644
--- /dev/null
+++ b/test/command/4598.md
@@ -0,0 +1,10 @@
+```
+% pandoc -f rst
+`x`__
+
+__ `xy`_
+
+.. _`xy`: http://xy.org
+^D
+<p><a href="http://xy.org">x</a></p>
+```
diff --git a/test/command/sloppypar.md b/test/command/sloppypar.md
new file mode 100644
--- /dev/null
+++ b/test/command/sloppypar.md
@@ -0,0 +1,23 @@
+```
+% pandoc -f latex+raw_tex -t native
+\begin{sloppypar}
+Sequi id qui facere et incidunt ut. Et fuga ut voluptate enim qui. Odit unde magni ipsam dicta modi. Modi soluta velit est aut aut possimus.
+
+Qui et temporibus explicabo. Esse ab ut quidem. Vel qui perspiciatis quae odio consectetur alias non sed. Quo consectetur libero omnis quos eius ad vel.
+\end{sloppypar}
+^D
+[Para [Str "Sequi",Space,Str "id",Space,Str "qui",Space,Str "facere",Space,Str "et",Space,Str "incidunt",Space,Str "ut.",Space,Str "Et",Space,Str "fuga",Space,Str "ut",Space,Str "voluptate",Space,Str "enim",Space,Str "qui.",Space,Str "Odit",Space,Str "unde",Space,Str "magni",Space,Str "ipsam",Space,Str "dicta",Space,Str "modi.",Space,Str "Modi",Space,Str "soluta",Space,Str "velit",Space,Str "est",Space,Str "aut",Space,Str "aut",Space,Str "possimus."]
+,Para [Str "Qui",Space,Str "et",Space,Str "temporibus",Space,Str "explicabo.",Space,Str "Esse",Space,Str "ab",Space,Str "ut",Space,Str "quidem.",Space,Str "Vel",Space,Str "qui",Space,Str "perspiciatis",Space,Str "quae",Space,Str "odio",Space,Str "consectetur",Space,Str "alias",Space,Str "non",Space,Str "sed.",Space,Str "Quo",Space,Str "consectetur",Space,Str "libero",Space,Str "omnis",Space,Str "quos",Space,Str "eius",Space,Str "ad",Space,Str "vel."]]
+```
+
+```
+% pandoc -f latex -t native
+\begin{sloppypar}
+Sequi id qui facere et incidunt ut. Et fuga ut voluptate enim qui. Odit unde magni ipsam dicta modi. Modi soluta velit est aut aut possimus.
+
+Qui et temporibus explicabo. Esse ab ut quidem. Vel qui perspiciatis quae odio consectetur alias non sed. Quo consectetur libero omnis quos eius ad vel.
+\end{sloppypar}
+^D
+[Para [Str "Sequi",Space,Str "id",Space,Str "qui",Space,Str "facere",Space,Str "et",Space,Str "incidunt",Space,Str "ut.",Space,Str "Et",Space,Str "fuga",Space,Str "ut",Space,Str "voluptate",Space,Str "enim",Space,Str "qui.",Space,Str "Odit",Space,Str "unde",Space,Str "magni",Space,Str "ipsam",Space,Str "dicta",Space,Str "modi.",Space,Str "Modi",Space,Str "soluta",Space,Str "velit",Space,Str "est",Space,Str "aut",Space,Str "aut",Space,Str "possimus."]
+,Para [Str "Qui",Space,Str "et",Space,Str "temporibus",Space,Str "explicabo.",Space,Str "Esse",Space,Str "ab",Space,Str "ut",Space,Str "quidem.",Space,Str "Vel",Space,Str "qui",Space,Str "perspiciatis",Space,Str "quae",Space,Str "odio",Space,Str "consectetur",Space,Str "alias",Space,Str "non",Space,Str "sed.",Space,Str "Quo",Space,Str "consectetur",Space,Str "libero",Space,Str "omnis",Space,Str "quos",Space,Str "eius",Space,Str "ad",Space,Str "vel."]]
+```
diff --git a/test/docx/adjacent_codeblocks.docx b/test/docx/adjacent_codeblocks.docx
new file mode 100644
Binary files /dev/null and b/test/docx/adjacent_codeblocks.docx differ
diff --git a/test/docx/adjacent_codeblocks.native b/test/docx/adjacent_codeblocks.native
new file mode 100644
--- /dev/null
+++ b/test/docx/adjacent_codeblocks.native
@@ -0,0 +1,6 @@
+[Para [Str "Next,",Space,Str "open",Space,Str "the",Space,Str "terminal",Space,Str "window.",Space,Str "Using",Space,Str "the",Space,Str "terminal",Space,Str "window,",Space,Str "run",Space,Str "the",Space,Str "\"ifconfig",Space,Str "-a\"",Space,Str "command",Space,Str "to",Space,Str "list",Space,Str "all",Space,Str "the",Space,Str "interfaces",Space,Str "on",Space,Str "your",Space,Str "system,",Space,Str "as",Space,Str "shown",Space,Str "here."]
+,CodeBlock ("",[],[]) "# ifconfig -a\neth0      Link encap:Ethernet  HWaddr 00:0c:29:69:12:7c  \n          inet addr:172.16.0.108  Bcast:172.16.0.255  Mask:255.255.255.0\n          inet6 addr: fc00:660:0:1:20c:29ff:fe69:127c/64 Scope:Global\n          inet6 addr: fe80::20c:29ff:fe69:127c/64 Scope:Link\n          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1\n          RX packets:9859 errors:0 dropped:0 overruns:0 frame:0\n          TX packets:1399 errors:0 dropped:0 overruns:0 carrier:0\n          collisions:0 txqueuelen:1000 \n          RX bytes:1920894 (1.8 MiB)  TX bytes:233088 (227.6 KiB)\n          Interrupt:19 Base address:0x2000 \n\nlo        Link encap:Local Loopback  \n          inet addr:127.0.0.1  Mask:255.0.0.0\n          inet6 addr: ::1/128 Scope:Host\n          UP LOOPBACK RUNNING  MTU:65536  Metric:1\n          RX packets:372 errors:0 dropped:0 overruns:0 frame:0\n          TX packets:372 errors:0 dropped:0 overruns:0 carrier:0\n          collisions:0 txqueuelen:0 \n          RX bytes:22320 (21.7 KiB)  TX bytes:22320 (21.7 KiB)\n\nwlan0     Link encap:Ethernet  HWaddr 00:c0:ca:85:00:ba  \n          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1\n          RX packets:0 errors:0 dropped:0 overruns:0 frame:0\n          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0\n          collisions:0 txqueuelen:1000 \n          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)"
+,Para [Str "The",Space,Str "ALFA",Space,Str "wireless",Space,Str "card",Space,Str "is",Space,Str "represented",Space,Str "by",Space,Str "the",Space,Str "\"wlan0\"",Space,Str "interface."]
+,Para [Str "In",Space,Str "addition",Space,Str "to",Space,Str "the",Space,Str "interfaces",Space,Str "shown",Space,Str "in",Space,Str "the",Space,Str "ifconfig",Space,Str "output,",Space,Str "there",Space,Str "is",Space,Str "another",Space,Str "interface",Space,Str "known",Space,Str "as",Space,Str "the",Space,Emph [Str "wireless",Space,Str "physical",Space,Str "interface"],Str ".",Space,Str "We",Space,Str "can",Space,Str "identify",Space,Str "this",Space,Str "interface",Space,Str "by",Space,Str "listing",Space,Str "the",Space,Str "contents",Space,Str "of",Space,Str "the",Space,Str "/sys/class/ieee80211",Space,Str "directory,",Space,Str "as",Space,Str "shown."]
+,CodeBlock ("",[],[]) "# ls /sys/class/ieee80211/\nphy0"
+,Para [Str "The",Space,Str "\"phy0\"",Space,Str "interface",Space,Str "is",Space,Str "the",Space,Str "parent",Space,Str "interface",Space,Str "used",Space,Str "to",Space,Str "create",Space,Str "child",Space,Str "interfaces.",Space,Str "Note",Space,Str "that",Space,Str "if",Space,Str "you",Space,Str "unplug",Space,Str "and",Space,Str "replug",Space,Str "the",Space,Str "USB",Space,Str "interface,",Space,Str "the",Space,Str "\"phy\"",Space,Str "interface",Space,Str "number",Space,Str "will",Space,Str "increment",Space,Str "by",Space,Str "one",Space,Str "until",Space,Str "you",Space,Str "reboot",Space,Str "your",Space,Str "system."]]
diff --git a/test/docx/block_quotes.docx b/test/docx/block_quotes.docx
Binary files a/test/docx/block_quotes.docx and b/test/docx/block_quotes.docx differ
diff --git a/test/docx/char_styles.docx b/test/docx/char_styles.docx
Binary files a/test/docx/char_styles.docx and b/test/docx/char_styles.docx differ
diff --git a/test/docx/deep_normalize.docx b/test/docx/deep_normalize.docx
Binary files a/test/docx/deep_normalize.docx and b/test/docx/deep_normalize.docx differ
diff --git a/test/docx/drop_cap.docx b/test/docx/drop_cap.docx
Binary files a/test/docx/drop_cap.docx and b/test/docx/drop_cap.docx differ
diff --git a/test/docx/hanging_indent.docx b/test/docx/hanging_indent.docx
Binary files a/test/docx/hanging_indent.docx and b/test/docx/hanging_indent.docx differ
diff --git a/test/docx/headers.docx b/test/docx/headers.docx
Binary files a/test/docx/headers.docx and b/test/docx/headers.docx differ
diff --git a/test/docx/inline_formatting.docx b/test/docx/inline_formatting.docx
Binary files a/test/docx/inline_formatting.docx and b/test/docx/inline_formatting.docx differ
diff --git a/test/docx/inline_images.docx b/test/docx/inline_images.docx
Binary files a/test/docx/inline_images.docx and b/test/docx/inline_images.docx differ
diff --git a/test/docx/link_in_notes.docx b/test/docx/link_in_notes.docx
Binary files a/test/docx/link_in_notes.docx and b/test/docx/link_in_notes.docx differ
diff --git a/test/docx/links.docx b/test/docx/links.docx
Binary files a/test/docx/links.docx and b/test/docx/links.docx differ
diff --git a/test/docx/lists.docx b/test/docx/lists.docx
Binary files a/test/docx/lists.docx and b/test/docx/lists.docx differ
diff --git a/test/docx/metadata.docx b/test/docx/metadata.docx
Binary files a/test/docx/metadata.docx and b/test/docx/metadata.docx differ
diff --git a/test/docx/metadata_after_normal.docx b/test/docx/metadata_after_normal.docx
Binary files a/test/docx/metadata_after_normal.docx and b/test/docx/metadata_after_normal.docx differ
diff --git a/test/docx/normalize.docx b/test/docx/normalize.docx
Binary files a/test/docx/normalize.docx and b/test/docx/normalize.docx differ
diff --git a/test/docx/notes.docx b/test/docx/notes.docx
Binary files a/test/docx/notes.docx and b/test/docx/notes.docx differ
diff --git a/test/docx/numbered_header.docx b/test/docx/numbered_header.docx
Binary files a/test/docx/numbered_header.docx and b/test/docx/numbered_header.docx differ
diff --git a/test/docx/table_variable_width.native b/test/docx/table_variable_width.native
--- a/test/docx/table_variable_width.native
+++ b/test/docx/table_variable_width.native
@@ -6,8 +6,11 @@
  ,[Plain [Str "h5"]]]
  [[[Plain [Str "c11"]]
   ,[]
+  ,[]
+  ,[]
   ,[]]
  ,[[]
   ,[Plain [Str "c22"]]
   ,[Plain [Str "c23"]]
+  ,[]
   ,[]]]]
diff --git a/test/docx/table_with_list_cell.docx b/test/docx/table_with_list_cell.docx
Binary files a/test/docx/table_with_list_cell.docx and b/test/docx/table_with_list_cell.docx differ
diff --git a/test/docx/tables.docx b/test/docx/tables.docx
Binary files a/test/docx/tables.docx and b/test/docx/tables.docx differ
diff --git a/test/fb2/basic.fb2 b/test/fb2/basic.fb2
--- a/test/fb2/basic.fb2
+++ b/test/fb2/basic.fb2
@@ -1,3 +1,75 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink"><description><title-info><genre>unrecognised</genre></title-info><document-info><program-used>pandoc</program-used></document-info></description><body><title><p /></title><section><title><p>Top-level title</p></title><section><title><p>Section</p></title><section><title><p>Subsection</p></title><p>This <emphasis>emphasized</emphasis> <strong>strong</strong> <code>verbatim</code> markdown. See this link<a l:href="#l1" type="note"><sup>[1]</sup></a>.</p><p>Ordered list:</p><p>1. one</p><p>2. two</p><p>3. three</p><cite><p>Blockquote is for citatons.</p></cite><empty-line /><p><code>Code</code></p><p><code>block</code></p><p><code>is</code></p><p><code>for</code></p><p><code>code.</code></p><empty-line /><p><strikethrough>Strikeout</strikethrough> is Pandoc’s extension. Superscript and subscripts too: H<sub>2</sub>O is a liquid<a l:href="#n2" type="note"><sup>[2]</sup></a>. 2<sup>10</sup> is 1024.</p><p>Math is another Pandoc extension: <code>E = m c^2</code>.</p></section></section></section></body><body name="notes"><section id="l1"><title><p>1</p></title><p><code>http://example.com/</code></p></section><section id="n2"><title><p>2</p></title><p>Sometimes.</p></section></body></FictionBook>
-
+<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">
+<description>
+<title-info>
+<genre>unrecognised</genre>
+</title-info>
+<document-info>
+<program-used>pandoc</program-used>
+</document-info>
+</description>
+<body>
+<title>
+<p />
+</title>
+<section>
+<title>
+<p>Top-level title</p>
+</title>
+<section>
+<title>
+<p>Section</p>
+</title>
+<section>
+<title>
+<p>Subsection</p>
+</title>
+<p>This <emphasis>emphasized</emphasis> <strong>strong</strong> <code>verbatim</code> markdown.
+See this <a l:href="http://example.com/">link</a>.</p>
+<p>Ordered list:</p>
+<p>1. one</p>
+<p>2. two</p>
+<p>3. three</p>
+<cite>
+<p>Blockquote
+is
+for
+citatons.</p>
+</cite>
+<empty-line />
+<p>
+<code>Code</code>
+</p>
+<p>
+<code>block</code>
+</p>
+<p>
+<code>is</code>
+</p>
+<p>
+<code>for</code>
+</p>
+<p>
+<code>code.</code>
+</p>
+<empty-line />
+<p>
+<strikethrough>Strikeout</strikethrough> is Pandoc’s extension.
+Superscript and subscripts too: H<sub>2</sub>O is a liquid<a l:href="#n1" type="note">
+<sup>[1]</sup>
+</a>.
+2<sup>10</sup> is 1024.</p>
+<p>Math is another Pandoc extension: <code>E = m c^2</code>.</p>
+</section>
+</section>
+</section>
+</body>
+<body name="notes">
+<section id="n1">
+<title>
+<p>1</p>
+</title>
+<p>Sometimes.</p>
+</section>
+</body>
+</FictionBook>
diff --git a/test/fb2/meta.fb2 b/test/fb2/meta.fb2
new file mode 100644
--- /dev/null
+++ b/test/fb2/meta.fb2
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink"><description><title-info><genre>unrecognised</genre><book-title>Book title</book-title><annotation><p>This is the abstract.</p>It consists of two paragraphs.</annotation></title-info><document-info><program-used>pandoc</program-used></document-info></description><body><title><p>Book title</p></title></body></FictionBook>
+
diff --git a/test/fb2/meta.markdown b/test/fb2/meta.markdown
new file mode 100644
--- /dev/null
+++ b/test/fb2/meta.markdown
@@ -0,0 +1,7 @@
+---
+title: Book title
+abstract: |
+  This is the abstract.
+
+  It consists of two paragraphs.
+---
diff --git a/test/fb2/reader/emphasis.fb2 b/test/fb2/reader/emphasis.fb2
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/emphasis.fb2
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">
+	<body>
+		<section>
+			<p>Plain, <strong>strong</strong>, <emphasis>emphasis</emphasis>, <strong><emphasis>strong emphasis</emphasis></strong>, <emphasis><strong>emphasized strong</strong></emphasis>.</p>
+			<p>Strikethrough: <strikethrough>deleted</strikethrough></p>
+			<p><sub>Subscript</sub> and <sup>superscript</sup></p>
+			<p>Some <code>code</code></p>
+		</section>
+	</body>
+</FictionBook>
diff --git a/test/fb2/reader/emphasis.native b/test/fb2/reader/emphasis.native
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/emphasis.native
@@ -0,0 +1,6 @@
+Pandoc (Meta {unMeta = fromList []})
+[Div ("",["section"],[])
+ [Para [Str "Plain,",Space,Strong [Str "strong"],Str ",",Space,Emph [Str "emphasis"],Str ",",Space,Strong [Emph [Str "strong",Space,Str "emphasis"]],Str ",",Space,Emph [Strong [Str "emphasized",Space,Str "strong"]],Str "."]
+ ,Para [Str "Strikethrough:",Space,Strikeout [Str "deleted"]]
+ ,Para [Subscript [Str "Subscript"],Space,Str "and",Space,Superscript [Str "superscript"]]
+ ,Para [Str "Some",Space,Code ("",[],[]) "code"]]]
diff --git a/test/fb2/reader/epigraph.fb2 b/test/fb2/reader/epigraph.fb2
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/epigraph.fb2
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">
+	<body>
+		<epigraph>
+			<p>Body epigraph</p>
+		</epigraph>
+		<section>
+			<epigraph>
+				<p>Section epigraph</p>
+			</epigraph>
+			<section>
+				<epigraph>
+					<p>Subsection epigraph</p>
+				</epigraph>
+			</section>
+		</section>
+	</body>
+</FictionBook>
diff --git a/test/fb2/reader/epigraph.native b/test/fb2/reader/epigraph.native
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/epigraph.native
@@ -0,0 +1,9 @@
+Pandoc (Meta {unMeta = fromList []})
+[Div ("",["epigraph"],[])
+ [Para [Str "Body",Space,Str "epigraph"]]
+,Div ("",["section"],[])
+ [Div ("",["epigraph"],[])
+  [Para [Str "Section",Space,Str "epigraph"]]
+ ,Div ("",["section"],[])
+  [Div ("",["epigraph"],[])
+   [Para [Str "Subsection",Space,Str "epigraph"]]]]]
diff --git a/test/fb2/reader/meta.fb2 b/test/fb2/reader/meta.fb2
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/meta.fb2
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">
+	<description>
+		<title-info>
+			<author>
+				<first-name>First</first-name>
+				<middle-name>Middle</middle-name>
+				<last-name>Last</last-name>
+			</author>
+			<author>
+				<first-name>Another</first-name>
+				<last-name>Author</last-name>
+			</author>
+			<book-title>Book title</book-title>
+			<annotation>
+				<p>Book annotation</p>
+				<p>Second paragraph of book annotation</p>
+			</annotation>
+			<keywords>foo, bar, baz</keywords>
+			<date>2018</date>
+		</title-info>
+	</description>
+	<body>
+		<title><p>Body title</p></title>
+	</body>
+</FictionBook>
diff --git a/test/fb2/reader/meta.native b/test/fb2/reader/meta.native
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/meta.native
@@ -0,0 +1,2 @@
+Pandoc (Meta {unMeta = fromList [("abstract",MetaBlocks [Para [Str "Book",Space,Str "annotation"],Para [Str "Second",Space,Str "paragraph",Space,Str "of",Space,Str "book",Space,Str "annotation"]]),("author",MetaList [MetaInlines [Str "First",Space,Str "Middle",Space,Str "Last"],MetaInlines [Str "Another",Space,Str "Author"]]),("date",MetaInlines [Str "2018"]),("keywords",MetaList [MetaString "foo",MetaString "bar",MetaString "baz"]),("title",MetaInlines [Str "Book",Space,Str "title"])]})
+[Header 1 ("",[],[]) [Str "Body",Space,Str "title"]]
diff --git a/test/fb2/reader/poem.fb2 b/test/fb2/reader/poem.fb2
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/poem.fb2
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">
+	<body>
+		<section>
+			<poem>
+				<title>
+					<p>Poem title</p>
+				</title>
+				<epigraph>
+					<p>Poem epigraph</p>
+				</epigraph>
+				<stanza>
+					<subtitle>Subtitle</subtitle>
+					<title>
+						<p>First stanza title</p>
+					</title>
+					<v>Verse</v>
+					<v><emphasis>More</emphasis> verse</v>
+				</stanza>
+				<stanza>
+					<v>One more stanza</v>
+				</stanza>
+				<text-author>Author</text-author>
+				<date>April 2018</date>
+			</poem>
+		</section>
+	</body>
+</FictionBook>
diff --git a/test/fb2/reader/poem.native b/test/fb2/reader/poem.native
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/poem.native
@@ -0,0 +1,14 @@
+Pandoc (Meta {unMeta = fromList []})
+[Div ("",["section"],[])
+ [Header 2 ("",[],[]) [Str "Poem",Space,Str "title"]
+ ,Div ("",["epigraph"],[])
+  [Para [Str "Poem",Space,Str "epigraph"]]
+ ,Header 2 ("",["unnumbered"],[]) [Str "Subtitle"]
+ ,Header 2 ("",[],[]) [Str "First",Space,Str "stanza",Space,Str "title"]
+ ,LineBlock
+  [[Str "Verse"]
+  ,[Emph [Str "More"],Space,Str "verse"]]
+ ,LineBlock
+  [[Str "One",Space,Str "more",Space,Str "stanza"]]
+ ,Para [Str "Author"]
+ ,Para [Str "April",Space,Str "2018"]]]
diff --git a/test/fb2/reader/titles.fb2 b/test/fb2/reader/titles.fb2
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/titles.fb2
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">
+	<body>
+		<title><p>Body title</p></title>
+		<section>
+			<title><p>Section title</p></title>
+			<section>
+				<title>
+					<p>Subsection title</p>
+					<p>with multiple paragraphs</p>
+				</title>
+			</section>
+			<section>
+				<title><p>Another subsection title</p></title>
+			</section>
+		</section>
+	</body>
+</FictionBook>
diff --git a/test/fb2/reader/titles.native b/test/fb2/reader/titles.native
new file mode 100644
--- /dev/null
+++ b/test/fb2/reader/titles.native
@@ -0,0 +1,8 @@
+Pandoc (Meta {unMeta = fromList []})
+[Header 1 ("",[],[]) [Str "Body",Space,Str "title"]
+,Div ("",["section"],[])
+ [Header 2 ("",[],[]) [Str "Section",Space,Str "title"]
+ ,Div ("",["section"],[])
+  [Header 3 ("",[],[]) [Str "Subsection",Space,Str "title",LineBreak,Str "with",Space,Str "multiple",Space,Str "paragraphs"]]
+ ,Div ("",["section"],[])
+  [Header 3 ("",[],[]) [Str "Another",Space,Str "subsection",Space,Str "title"]]]]
diff --git a/test/fb2/titles.fb2 b/test/fb2/titles.fb2
--- a/test/fb2/titles.fb2
+++ b/test/fb2/titles.fb2
@@ -1,3 +1,3 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink"><description><title-info><genre>unrecognised</genre></title-info><document-info><program-used>pandoc</program-used></document-info></description><body><title><p /></title><section><title><p>Simple title</p></title><p>This example tests if Pandoc doesn’t insert forbidden elements in FictionBook titles.</p></section><section><title><p>Emphasized Strong Title</p></title></section></body></FictionBook>
+<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink"><description><title-info><genre>unrecognised</genre></title-info><document-info><program-used>pandoc</program-used></document-info></description><body><title><p /></title><section><title><p>Simple title</p></title><p>This example tests FictionBook titles.</p></section><section><title><p><emphasis>Emphasized</emphasis> <strong>Strong</strong> Title</p></title></section></body></FictionBook>
 
diff --git a/test/fb2/titles.markdown b/test/fb2/titles.markdown
--- a/test/fb2/titles.markdown
+++ b/test/fb2/titles.markdown
@@ -1,6 +1,6 @@
 # Simple title
 
-This example tests if Pandoc doesn't insert forbidden elements in FictionBook titles.
+This example tests FictionBook titles.
 
 # *Emphasized* **Strong** Title
 
diff --git a/test/lhs-test.rst b/test/lhs-test.rst
--- a/test/lhs-test.rst
+++ b/test/lhs-test.rst
@@ -6,9 +6,9 @@
 
 .. code:: haskell
 
-    unsplit :: (Arrow a) => (b -> c -> d) -> a (b, c) d
-    unsplit = arr . uncurry
-              -- arr (\op (x,y) -> x `op` y)
+   unsplit :: (Arrow a) => (b -> c -> d) -> a (b, c) d
+   unsplit = arr . uncurry
+             -- arr (\op (x,y) -> x `op` y)
 
 ``(***)`` combines two arrows into a new arrow by running the two arrows on a
 pair of values (one arrow on the first item of the pair and one arrow on the
@@ -16,8 +16,8 @@
 
 ::
 
-    f *** g = first f >>> second g
+   f *** g = first f >>> second g
 
 Block quote:
 
-    foo bar
+   foo bar
diff --git a/test/lhs-test.rst+lhs b/test/lhs-test.rst+lhs
--- a/test/lhs-test.rst+lhs
+++ b/test/lhs-test.rst+lhs
@@ -14,8 +14,8 @@
 
 ::
 
-    f *** g = first f >>> second g
+   f *** g = first f >>> second g
 
 Block quote:
 
-    foo bar
+   foo bar
diff --git a/test/pptx/endnotes_templated.pptx b/test/pptx/endnotes_templated.pptx
Binary files a/test/pptx/endnotes_templated.pptx and b/test/pptx/endnotes_templated.pptx differ
diff --git a/test/pptx/endnotes_toc_templated.pptx b/test/pptx/endnotes_toc_templated.pptx
Binary files a/test/pptx/endnotes_toc_templated.pptx and b/test/pptx/endnotes_toc_templated.pptx differ
diff --git a/test/pptx/images_templated.pptx b/test/pptx/images_templated.pptx
Binary files a/test/pptx/images_templated.pptx and b/test/pptx/images_templated.pptx differ
diff --git a/test/pptx/lists_templated.pptx b/test/pptx/lists_templated.pptx
Binary files a/test/pptx/lists_templated.pptx and b/test/pptx/lists_templated.pptx differ
diff --git a/test/pptx/slide_breaks_slide_level_1_templated.pptx b/test/pptx/slide_breaks_slide_level_1_templated.pptx
Binary files a/test/pptx/slide_breaks_slide_level_1_templated.pptx and b/test/pptx/slide_breaks_slide_level_1_templated.pptx differ
diff --git a/test/pptx/slide_breaks_templated.pptx b/test/pptx/slide_breaks_templated.pptx
Binary files a/test/pptx/slide_breaks_templated.pptx and b/test/pptx/slide_breaks_templated.pptx differ
diff --git a/test/pptx/slide_breaks_toc_templated.pptx b/test/pptx/slide_breaks_toc_templated.pptx
Binary files a/test/pptx/slide_breaks_toc_templated.pptx and b/test/pptx/slide_breaks_toc_templated.pptx differ
diff --git a/test/pptx/speaker_notes_afterseps.native b/test/pptx/speaker_notes_afterseps.native
new file mode 100644
--- /dev/null
+++ b/test/pptx/speaker_notes_afterseps.native
@@ -0,0 +1,33 @@
+[Para [Image ("",[],[]) [Str "The",Space,Str "moon"] ("lalune.jpg","fig:")]
+,Div ("",["notes"],[])
+ [Para [Str "chicken",Space,Str "and",Space,Str "dumplings"]]
+,Table [Str "Demonstration",Space,Str "of",Space,Str "simple",Space,Str "table",Space,Str "syntax,",Space,Str "with",Space,Str "alignment"] [AlignRight,AlignLeft,AlignCenter,AlignDefault] [0.0,0.0,0.0,0.0]
+ [[Plain [Str "Right"]]
+ ,[Plain [Str "Left"]]
+ ,[Plain [Str "Center"]]
+ ,[Plain [Str "Default"]]]
+ [[[Plain [Str "12"]]
+  ,[Plain [Str "12"]]
+  ,[Plain [Str "12"]]
+  ,[Plain [Str "12"]]]
+ ,[[Plain [Str "123"]]
+  ,[Plain [Str "123"]]
+  ,[Plain [Str "123"]]
+  ,[Plain [Str "123"]]]
+ ,[[Plain [Str "1"]]
+  ,[Plain [Str "1"]]
+  ,[Plain [Str "1"]]
+  ,[Plain [Str "1"]]]]
+,Div ("",["notes"],[])
+ [Para [Str "foo",Space,Str "bar"]]
+,Div ("",["columns"],[])
+ [Div ("",["column"],[])
+  [BulletList
+   [[Para [Str "some",Space,Str "stuff"]]
+   ,[Para [Str "some",Space,Str "more",Space,Str "stuff"]]]
+  ,Div ("",["notes"],[])
+   [Para [Str "Some",Space,Str "notes",Space,Str "inside",Space,Str "a",Space,Str "column"]]]
+ ,Div ("",["column"],[])
+  [Para [Str "Some",Space,Str "other",Space,Emph [Str "stuff"]]]]
+,Div ("",["notes"],[])
+ [Para [Str "Some",Space,Str "notes",Space,Str "outside",Space,Str "the",Space,Str "column"]]]
diff --git a/test/pptx/speaker_notes_afterseps.pptx b/test/pptx/speaker_notes_afterseps.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/speaker_notes_afterseps.pptx differ
diff --git a/test/pptx/speaker_notes_afterseps_templated.pptx b/test/pptx/speaker_notes_afterseps_templated.pptx
new file mode 100644
Binary files /dev/null and b/test/pptx/speaker_notes_afterseps_templated.pptx differ
diff --git a/test/pptx/tables_templated.pptx b/test/pptx/tables_templated.pptx
Binary files a/test/pptx/tables_templated.pptx and b/test/pptx/tables_templated.pptx differ
diff --git a/test/s5-fancy.html b/test/s5-fancy.html
--- a/test/s5-fancy.html
+++ b/test/s5-fancy.html
@@ -26,207 +26,7 @@
   <link rel="stylesheet" href="s5/default/opera.css" type="text/css" media="projection" id="operaFix" />
   <!-- S5 JS -->
   <script src="s5/default/slides.js" type="text/javascript"></script>
-  <script type="text/javascript">/*<![CDATA[*/
-  /*
-  LaTeXMathML.js from http://math.etsu.edu/LaTeXMathML/
-  Adapted by Jeff Knisely and Douglas Woodall from ASCIIMathML.js v. 1.4.7,
-  (c) 2005 Peter Jipsen http://www.chapman.edu/~jipsen.
-  Released under the GNU General Public License version 2 or later.
-  See the GNU General Public License (at http://www.gnu.org/copyleft/gpl.html)
-  for more details.
-  */
-  var checkForMathML=true;var notifyIfNoMathML=true;var alertIfNoMathML=false;var mathcolor="";var mathfontfamily="";var showasciiformulaonhover=true;var isIE=document.createElementNS==null;if(document.getElementById==null)
-  alert("This webpage requires a recent browser such as \nMozilla/Netscape 7+ or Internet Explorer 6+MathPlayer")
-  function AMcreateElementXHTML(t){if(isIE)return document.createElement(t);else return document.createElementNS("http://www.w3.org/1999/xhtml",t);}
-  function AMnoMathMLNote(){var nd=AMcreateElementXHTML("h3");nd.setAttribute("align","center")
-  nd.appendChild(AMcreateElementXHTML("p"));nd.appendChild(document.createTextNode("To view the "));var an=AMcreateElementXHTML("a");an.appendChild(document.createTextNode("LaTeXMathML"));an.setAttribute("href","http://www.maths.nott.ac.uk/personal/drw/lm.html");nd.appendChild(an);nd.appendChild(document.createTextNode(" notation use Internet Explorer 6+"));an=AMcreateElementXHTML("a");an.appendChild(document.createTextNode("MathPlayer"));an.setAttribute("href","http://www.dessci.com/en/products/mathplayer/download.htm");nd.appendChild(an);nd.appendChild(document.createTextNode(" or Netscape/Mozilla/Firefox"));nd.appendChild(AMcreateElementXHTML("p"));return nd;}
-  function AMisMathMLavailable(){if(navigator.appName.slice(0,8)=="Netscape")
-  if(navigator.appVersion.slice(0,1)>="5")return null;else return AMnoMathMLNote();else if(navigator.appName.slice(0,9)=="Microsoft")
-  try{var ActiveX=new ActiveXObject("MathPlayer.Factory.1");return null;}catch(e){return AMnoMathMLNote();}
-  else return AMnoMathMLNote();}
-  var AMcal=[0xEF35,0x212C,0xEF36,0xEF37,0x2130,0x2131,0xEF38,0x210B,0x2110,0xEF39,0xEF3A,0x2112,0x2133,0xEF3B,0xEF3C,0xEF3D,0xEF3E,0x211B,0xEF3F,0xEF40,0xEF41,0xEF42,0xEF43,0xEF44,0xEF45,0xEF46];var AMfrk=[0xEF5D,0xEF5E,0x212D,0xEF5F,0xEF60,0xEF61,0xEF62,0x210C,0x2111,0xEF63,0xEF64,0xEF65,0xEF66,0xEF67,0xEF68,0xEF69,0xEF6A,0x211C,0xEF6B,0xEF6C,0xEF6D,0xEF6E,0xEF6F,0xEF70,0xEF71,0x2128];var AMbbb=[0xEF8C,0xEF8D,0x2102,0xEF8E,0xEF8F,0xEF90,0xEF91,0x210D,0xEF92,0xEF93,0xEF94,0xEF95,0xEF96,0x2115,0xEF97,0x2119,0x211A,0x211D,0xEF98,0xEF99,0xEF9A,0xEF9B,0xEF9C,0xEF9D,0xEF9E,0x2124];var CONST=0,UNARY=1,BINARY=2,INFIX=3,LEFTBRACKET=4,RIGHTBRACKET=5,SPACE=6,UNDEROVER=7,DEFINITION=8,TEXT=9,BIG=10,LONG=11,STRETCHY=12,MATRIX=13;var AMsqrt={input:"\\sqrt",tag:"msqrt",output:"sqrt",ttype:UNARY},AMroot={input:"\\root",tag:"mroot",output:"root",ttype:BINARY},AMfrac={input:"\\frac",tag:"mfrac",output:"/",ttype:BINARY},AMover={input:"\\stackrel",tag:"mover",output:"stackrel",ttype:BINARY},AMatop={input:"\\atop",tag:"mfrac",output:"",ttype:INFIX},AMchoose={input:"\\choose",tag:"mfrac",output:"",ttype:INFIX},AMsub={input:"_",tag:"msub",output:"_",ttype:INFIX},AMsup={input:"^",tag:"msup",output:"^",ttype:INFIX},AMtext={input:"\\mathrm",tag:"mtext",output:"text",ttype:TEXT},AMmbox={input:"\\mbox",tag:"mtext",output:"mbox",ttype:TEXT};var AMsymbols=[{input:"\\alpha",tag:"mi",output:"\u03B1",ttype:CONST},{input:"\\beta",tag:"mi",output:"\u03B2",ttype:CONST},{input:"\\gamma",tag:"mi",output:"\u03B3",ttype:CONST},{input:"\\delta",tag:"mi",output:"\u03B4",ttype:CONST},{input:"\\epsilon",tag:"mi",output:"\u03B5",ttype:CONST},{input:"\\varepsilon",tag:"mi",output:"\u025B",ttype:CONST},{input:"\\zeta",tag:"mi",output:"\u03B6",ttype:CONST},{input:"\\eta",tag:"mi",output:"\u03B7",ttype:CONST},{input:"\\theta",tag:"mi",output:"\u03B8",ttype:CONST},{input:"\\vartheta",tag:"mi",output:"\u03D1",ttype:CONST},{input:"\\iota",tag:"mi",output:"\u03B9",ttype:CONST},{input:"\\kappa",tag:"mi",output:"\u03BA",ttype:CONST},{input:"\\lambda",tag:"mi",output:"\u03BB",ttype:CONST},{input:"\\mu",tag:"mi",output:"\u03BC",ttype:CONST},{input:"\\nu",tag:"mi",output:"\u03BD",ttype:CONST},{input:"\\xi",tag:"mi",output:"\u03BE",ttype:CONST},{input:"\\pi",tag:"mi",output:"\u03C0",ttype:CONST},{input:"\\varpi",tag:"mi",output:"\u03D6",ttype:CONST},{input:"\\rho",tag:"mi",output:"\u03C1",ttype:CONST},{input:"\\varrho",tag:"mi",output:"\u03F1",ttype:CONST},{input:"\\varsigma",tag:"mi",output:"\u03C2",ttype:CONST},{input:"\\sigma",tag:"mi",output:"\u03C3",ttype:CONST},{input:"\\tau",tag:"mi",output:"\u03C4",ttype:CONST},{input:"\\upsilon",tag:"mi",output:"\u03C5",ttype:CONST},{input:"\\phi",tag:"mi",output:"\u03C6",ttype:CONST},{input:"\\varphi",tag:"mi",output:"\u03D5",ttype:CONST},{input:"\\chi",tag:"mi",output:"\u03C7",ttype:CONST},{input:"\\psi",tag:"mi",output:"\u03C8",ttype:CONST},{input:"\\omega",tag:"mi",output:"\u03C9",ttype:CONST},{input:"\\Gamma",tag:"mo",output:"\u0393",ttype:CONST},{input:"\\Delta",tag:"mo",output:"\u0394",ttype:CONST},{input:"\\Theta",tag:"mo",output:"\u0398",ttype:CONST},{input:"\\Lambda",tag:"mo",output:"\u039B",ttype:CONST},{input:"\\Xi",tag:"mo",output:"\u039E",ttype:CONST},{input:"\\Pi",tag:"mo",output:"\u03A0",ttype:CONST},{input:"\\Sigma",tag:"mo",output:"\u03A3",ttype:CONST},{input:"\\Upsilon",tag:"mo",output:"\u03A5",ttype:CONST},{input:"\\Phi",tag:"mo",output:"\u03A6",ttype:CONST},{input:"\\Psi",tag:"mo",output:"\u03A8",ttype:CONST},{input:"\\Omega",tag:"mo",output:"\u03A9",ttype:CONST},{input:"\\frac12",tag:"mo",output:"\u00BD",ttype:CONST},{input:"\\frac14",tag:"mo",output:"\u00BC",ttype:CONST},{input:"\\frac34",tag:"mo",output:"\u00BE",ttype:CONST},{input:"\\frac13",tag:"mo",output:"\u2153",ttype:CONST},{input:"\\frac23",tag:"mo",output:"\u2154",ttype:CONST},{input:"\\frac15",tag:"mo",output:"\u2155",ttype:CONST},{input:"\\frac25",tag:"mo",output:"\u2156",ttype:CONST},{input:"\\frac35",tag:"mo",output:"\u2157",ttype:CONST},{input:"\\frac45",tag:"mo",output:"\u2158",ttype:CONST},{input:"\\frac16",tag:"mo",output:"\u2159",ttype:CONST},{input:"\\frac56",tag:"mo",output:"\u215A",ttype:CONST},{input:"\\frac18",tag:"mo",output:"\u215B",ttype:CONST},{input:"\\frac38",tag:"mo",output:"\u215C",ttype:CONST},{input:"\\frac58",tag:"mo",output:"\u215D",ttype:CONST},{input:"\\frac78",tag:"mo",output:"\u215E",ttype:CONST},{input:"\\pm",tag:"mo",output:"\u00B1",ttype:CONST},{input:"\\mp",tag:"mo",output:"\u2213",ttype:CONST},{input:"\\triangleleft",tag:"mo",output:"\u22B2",ttype:CONST},{input:"\\triangleright",tag:"mo",output:"\u22B3",ttype:CONST},{input:"\\cdot",tag:"mo",output:"\u22C5",ttype:CONST},{input:"\\star",tag:"mo",output:"\u22C6",ttype:CONST},{input:"\\ast",tag:"mo",output:"\u002A",ttype:CONST},{input:"\\times",tag:"mo",output:"\u00D7",ttype:CONST},{input:"\\div",tag:"mo",output:"\u00F7",ttype:CONST},{input:"\\circ",tag:"mo",output:"\u2218",ttype:CONST},{input:"\\bullet",tag:"mo",output:"\u2022",ttype:CONST},{input:"\\oplus",tag:"mo",output:"\u2295",ttype:CONST},{input:"\\ominus",tag:"mo",output:"\u2296",ttype:CONST},{input:"\\otimes",tag:"mo",output:"\u2297",ttype:CONST},{input:"\\bigcirc",tag:"mo",output:"\u25CB",ttype:CONST},{input:"\\oslash",tag:"mo",output:"\u2298",ttype:CONST},{input:"\\odot",tag:"mo",output:"\u2299",ttype:CONST},{input:"\\land",tag:"mo",output:"\u2227",ttype:CONST},{input:"\\wedge",tag:"mo",output:"\u2227",ttype:CONST},{input:"\\lor",tag:"mo",output:"\u2228",ttype:CONST},{input:"\\vee",tag:"mo",output:"\u2228",ttype:CONST},{input:"\\cap",tag:"mo",output:"\u2229",ttype:CONST},{input:"\\cup",tag:"mo",output:"\u222A",ttype:CONST},{input:"\\sqcap",tag:"mo",output:"\u2293",ttype:CONST},{input:"\\sqcup",tag:"mo",output:"\u2294",ttype:CONST},{input:"\\uplus",tag:"mo",output:"\u228E",ttype:CONST},{input:"\\amalg",tag:"mo",output:"\u2210",ttype:CONST},{input:"\\bigtriangleup",tag:"mo",output:"\u25B3",ttype:CONST},{input:"\\bigtriangledown",tag:"mo",output:"\u25BD",ttype:CONST},{input:"\\dag",tag:"mo",output:"\u2020",ttype:CONST},{input:"\\dagger",tag:"mo",output:"\u2020",ttype:CONST},{input:"\\ddag",tag:"mo",output:"\u2021",ttype:CONST},{input:"\\ddagger",tag:"mo",output:"\u2021",ttype:CONST},{input:"\\lhd",tag:"mo",output:"\u22B2",ttype:CONST},{input:"\\rhd",tag:"mo",output:"\u22B3",ttype:CONST},{input:"\\unlhd",tag:"mo",output:"\u22B4",ttype:CONST},{input:"\\unrhd",tag:"mo",output:"\u22B5",ttype:CONST},{input:"\\sum",tag:"mo",output:"\u2211",ttype:UNDEROVER},{input:"\\prod",tag:"mo",output:"\u220F",ttype:UNDEROVER},{input:"\\bigcap",tag:"mo",output:"\u22C2",ttype:UNDEROVER},{input:"\\bigcup",tag:"mo",output:"\u22C3",ttype:UNDEROVER},{input:"\\bigwedge",tag:"mo",output:"\u22C0",ttype:UNDEROVER},{input:"\\bigvee",tag:"mo",output:"\u22C1",ttype:UNDEROVER},{input:"\\bigsqcap",tag:"mo",output:"\u2A05",ttype:UNDEROVER},{input:"\\bigsqcup",tag:"mo",output:"\u2A06",ttype:UNDEROVER},{input:"\\coprod",tag:"mo",output:"\u2210",ttype:UNDEROVER},{input:"\\bigoplus",tag:"mo",output:"\u2A01",ttype:UNDEROVER},{input:"\\bigotimes",tag:"mo",output:"\u2A02",ttype:UNDEROVER},{input:"\\bigodot",tag:"mo",output:"\u2A00",ttype:UNDEROVER},{input:"\\biguplus",tag:"mo",output:"\u2A04",ttype:UNDEROVER},{input:"\\int",tag:"mo",output:"\u222B",ttype:CONST},{input:"\\oint",tag:"mo",output:"\u222E",ttype:CONST},{input:":=",tag:"mo",output:":=",ttype:CONST},{input:"\\lt",tag:"mo",output:"<",ttype:CONST},{input:"\\gt",tag:"mo",output:">",ttype:CONST},{input:"\\ne",tag:"mo",output:"\u2260",ttype:CONST},{input:"\\neq",tag:"mo",output:"\u2260",ttype:CONST},{input:"\\le",tag:"mo",output:"\u2264",ttype:CONST},{input:"\\leq",tag:"mo",output:"\u2264",ttype:CONST},{input:"\\leqslant",tag:"mo",output:"\u2264",ttype:CONST},{input:"\\ge",tag:"mo",output:"\u2265",ttype:CONST},{input:"\\geq",tag:"mo",output:"\u2265",ttype:CONST},{input:"\\geqslant",tag:"mo",output:"\u2265",ttype:CONST},{input:"\\equiv",tag:"mo",output:"\u2261",ttype:CONST},{input:"\\ll",tag:"mo",output:"\u226A",ttype:CONST},{input:"\\gg",tag:"mo",output:"\u226B",ttype:CONST},{input:"\\doteq",tag:"mo",output:"\u2250",ttype:CONST},{input:"\\prec",tag:"mo",output:"\u227A",ttype:CONST},{input:"\\succ",tag:"mo",output:"\u227B",ttype:CONST},{input:"\\preceq",tag:"mo",output:"\u227C",ttype:CONST},{input:"\\succeq",tag:"mo",output:"\u227D",ttype:CONST},{input:"\\subset",tag:"mo",output:"\u2282",ttype:CONST},{input:"\\supset",tag:"mo",output:"\u2283",ttype:CONST},{input:"\\subseteq",tag:"mo",output:"\u2286",ttype:CONST},{input:"\\supseteq",tag:"mo",output:"\u2287",ttype:CONST},{input:"\\sqsubset",tag:"mo",output:"\u228F",ttype:CONST},{input:"\\sqsupset",tag:"mo",output:"\u2290",ttype:CONST},{input:"\\sqsubseteq",tag:"mo",output:"\u2291",ttype:CONST},{input:"\\sqsupseteq",tag:"mo",output:"\u2292",ttype:CONST},{input:"\\sim",tag:"mo",output:"\u223C",ttype:CONST},{input:"\\simeq",tag:"mo",output:"\u2243",ttype:CONST},{input:"\\approx",tag:"mo",output:"\u2248",ttype:CONST},{input:"\\cong",tag:"mo",output:"\u2245",ttype:CONST},{input:"\\Join",tag:"mo",output:"\u22C8",ttype:CONST},{input:"\\bowtie",tag:"mo",output:"\u22C8",ttype:CONST},{input:"\\in",tag:"mo",output:"\u2208",ttype:CONST},{input:"\\ni",tag:"mo",output:"\u220B",ttype:CONST},{input:"\\owns",tag:"mo",output:"\u220B",ttype:CONST},{input:"\\propto",tag:"mo",output:"\u221D",ttype:CONST},{input:"\\vdash",tag:"mo",output:"\u22A2",ttype:CONST},{input:"\\dashv",tag:"mo",output:"\u22A3",ttype:CONST},{input:"\\models",tag:"mo",output:"\u22A8",ttype:CONST},{input:"\\perp",tag:"mo",output:"\u22A5",ttype:CONST},{input:"\\smile",tag:"mo",output:"\u2323",ttype:CONST},{input:"\\frown",tag:"mo",output:"\u2322",ttype:CONST},{input:"\\asymp",tag:"mo",output:"\u224D",ttype:CONST},{input:"\\notin",tag:"mo",output:"\u2209",ttype:CONST},{input:"\\begin{eqnarray}",output:"X",ttype:MATRIX,invisible:true},{input:"\\begin{array}",output:"X",ttype:MATRIX,invisible:true},{input:"\\\\",output:"}&{",ttype:DEFINITION},{input:"\\end{eqnarray}",output:"}}",ttype:DEFINITION},{input:"\\end{array}",output:"}}",ttype:DEFINITION},{input:"\\big",tag:"mo",output:"X",atval:"1.2",ieval:"2.2",ttype:BIG},{input:"\\Big",tag:"mo",output:"X",atval:"1.6",ieval:"2.6",ttype:BIG},{input:"\\bigg",tag:"mo",output:"X",atval:"2.2",ieval:"3.2",ttype:BIG},{input:"\\Bigg",tag:"mo",output:"X",atval:"2.9",ieval:"3.9",ttype:BIG},{input:"\\left",tag:"mo",output:"X",ttype:LEFTBRACKET},{input:"\\right",tag:"mo",output:"X",ttype:RIGHTBRACKET},{input:"{",output:"{",ttype:LEFTBRACKET,invisible:true},{input:"}",output:"}",ttype:RIGHTBRACKET,invisible:true},{input:"(",tag:"mo",output:"(",atval:"1",ttype:STRETCHY},{input:"[",tag:"mo",output:"[",atval:"1",ttype:STRETCHY},{input:"\\lbrack",tag:"mo",output:"[",atval:"1",ttype:STRETCHY},{input:"\\{",tag:"mo",output:"{",atval:"1",ttype:STRETCHY},{input:"\\lbrace",tag:"mo",output:"{",atval:"1",ttype:STRETCHY},{input:"\\langle",tag:"mo",output:"\u2329",atval:"1",ttype:STRETCHY},{input:"\\lfloor",tag:"mo",output:"\u230A",atval:"1",ttype:STRETCHY},{input:"\\lceil",tag:"mo",output:"\u2308",atval:"1",ttype:STRETCHY},{input:")",tag:"mo",output:")",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"]",tag:"mo",output:"]",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rbrack",tag:"mo",output:"]",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\}",tag:"mo",output:"}",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rbrace",tag:"mo",output:"}",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rangle",tag:"mo",output:"\u232A",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rfloor",tag:"mo",output:"\u230B",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rceil",tag:"mo",output:"\u2309",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"|",tag:"mo",output:"\u2223",atval:"1",ttype:STRETCHY},{input:"\\|",tag:"mo",output:"\u2225",atval:"1",ttype:STRETCHY},{input:"\\vert",tag:"mo",output:"\u2223",atval:"1",ttype:STRETCHY},{input:"\\Vert",tag:"mo",output:"\u2225",atval:"1",ttype:STRETCHY},{input:"\\mid",tag:"mo",output:"\u2223",atval:"1",ttype:STRETCHY},{input:"\\parallel",tag:"mo",output:"\u2225",atval:"1",ttype:STRETCHY},{input:"/",tag:"mo",output:"/",atval:"1.01",ttype:STRETCHY},{input:"\\backslash",tag:"mo",output:"\u2216",atval:"1",ttype:STRETCHY},{input:"\\setminus",tag:"mo",output:"\\",ttype:CONST},{input:"\\!",tag:"mspace",atname:"width",atval:"-0.167em",ttype:SPACE},{input:"\\,",tag:"mspace",atname:"width",atval:"0.167em",ttype:SPACE},{input:"\\>",tag:"mspace",atname:"width",atval:"0.222em",ttype:SPACE},{input:"\\:",tag:"mspace",atname:"width",atval:"0.222em",ttype:SPACE},{input:"\\;",tag:"mspace",atname:"width",atval:"0.278em",ttype:SPACE},{input:"~",tag:"mspace",atname:"width",atval:"0.333em",ttype:SPACE},{input:"\\quad",tag:"mspace",atname:"width",atval:"1em",ttype:SPACE},{input:"\\qquad",tag:"mspace",atname:"width",atval:"2em",ttype:SPACE},{input:"\\prime",tag:"mo",output:"\u2032",ttype:CONST},{input:"'",tag:"mo",output:"\u02B9",ttype:CONST},{input:"''",tag:"mo",output:"\u02BA",ttype:CONST},{input:"'''",tag:"mo",output:"\u2034",ttype:CONST},{input:"''''",tag:"mo",output:"\u2057",ttype:CONST},{input:"\\ldots",tag:"mo",output:"\u2026",ttype:CONST},{input:"\\cdots",tag:"mo",output:"\u22EF",ttype:CONST},{input:"\\vdots",tag:"mo",output:"\u22EE",ttype:CONST},{input:"\\ddots",tag:"mo",output:"\u22F1",ttype:CONST},{input:"\\forall",tag:"mo",output:"\u2200",ttype:CONST},{input:"\\exists",tag:"mo",output:"\u2203",ttype:CONST},{input:"\\Re",tag:"mo",output:"\u211C",ttype:CONST},{input:"\\Im",tag:"mo",output:"\u2111",ttype:CONST},{input:"\\aleph",tag:"mo",output:"\u2135",ttype:CONST},{input:"\\hbar",tag:"mo",output:"\u210F",ttype:CONST},{input:"\\ell",tag:"mo",output:"\u2113",ttype:CONST},{input:"\\wp",tag:"mo",output:"\u2118",ttype:CONST},{input:"\\emptyset",tag:"mo",output:"\u2205",ttype:CONST},{input:"\\infty",tag:"mo",output:"\u221E",ttype:CONST},{input:"\\surd",tag:"mo",output:"\\sqrt{}",ttype:DEFINITION},{input:"\\partial",tag:"mo",output:"\u2202",ttype:CONST},{input:"\\nabla",tag:"mo",output:"\u2207",ttype:CONST},{input:"\\triangle",tag:"mo",output:"\u25B3",ttype:CONST},{input:"\\therefore",tag:"mo",output:"\u2234",ttype:CONST},{input:"\\angle",tag:"mo",output:"\u2220",ttype:CONST},{input:"\\diamond",tag:"mo",output:"\u22C4",ttype:CONST},{input:"\\Diamond",tag:"mo",output:"\u25C7",ttype:CONST},{input:"\\neg",tag:"mo",output:"\u00AC",ttype:CONST},{input:"\\lnot",tag:"mo",output:"\u00AC",ttype:CONST},{input:"\\bot",tag:"mo",output:"\u22A5",ttype:CONST},{input:"\\top",tag:"mo",output:"\u22A4",ttype:CONST},{input:"\\square",tag:"mo",output:"\u25AB",ttype:CONST},{input:"\\Box",tag:"mo",output:"\u25A1",ttype:CONST},{input:"\\wr",tag:"mo",output:"\u2240",ttype:CONST},{input:"\\arccos",tag:"mi",output:"arccos",ttype:UNARY,func:true},{input:"\\arcsin",tag:"mi",output:"arcsin",ttype:UNARY,func:true},{input:"\\arctan",tag:"mi",output:"arctan",ttype:UNARY,func:true},{input:"\\arg",tag:"mi",output:"arg",ttype:UNARY,func:true},{input:"\\cos",tag:"mi",output:"cos",ttype:UNARY,func:true},{input:"\\cosh",tag:"mi",output:"cosh",ttype:UNARY,func:true},{input:"\\cot",tag:"mi",output:"cot",ttype:UNARY,func:true},{input:"\\coth",tag:"mi",output:"coth",ttype:UNARY,func:true},{input:"\\csc",tag:"mi",output:"csc",ttype:UNARY,func:true},{input:"\\deg",tag:"mi",output:"deg",ttype:UNARY,func:true},{input:"\\det",tag:"mi",output:"det",ttype:UNARY,func:true},{input:"\\dim",tag:"mi",output:"dim",ttype:UNARY,func:true},{input:"\\exp",tag:"mi",output:"exp",ttype:UNARY,func:true},{input:"\\gcd",tag:"mi",output:"gcd",ttype:UNARY,func:true},{input:"\\hom",tag:"mi",output:"hom",ttype:UNARY,func:true},{input:"\\inf",tag:"mo",output:"inf",ttype:UNDEROVER},{input:"\\ker",tag:"mi",output:"ker",ttype:UNARY,func:true},{input:"\\lg",tag:"mi",output:"lg",ttype:UNARY,func:true},{input:"\\lim",tag:"mo",output:"lim",ttype:UNDEROVER},{input:"\\liminf",tag:"mo",output:"liminf",ttype:UNDEROVER},{input:"\\limsup",tag:"mo",output:"limsup",ttype:UNDEROVER},{input:"\\ln",tag:"mi",output:"ln",ttype:UNARY,func:true},{input:"\\log",tag:"mi",output:"log",ttype:UNARY,func:true},{input:"\\max",tag:"mo",output:"max",ttype:UNDEROVER},{input:"\\min",tag:"mo",output:"min",ttype:UNDEROVER},{input:"\\Pr",tag:"mi",output:"Pr",ttype:UNARY,func:true},{input:"\\sec",tag:"mi",output:"sec",ttype:UNARY,func:true},{input:"\\sin",tag:"mi",output:"sin",ttype:UNARY,func:true},{input:"\\sinh",tag:"mi",output:"sinh",ttype:UNARY,func:true},{input:"\\sup",tag:"mo",output:"sup",ttype:UNDEROVER},{input:"\\tan",tag:"mi",output:"tan",ttype:UNARY,func:true},{input:"\\tanh",tag:"mi",output:"tanh",ttype:UNARY,func:true},{input:"\\gets",tag:"mo",output:"\u2190",ttype:CONST},{input:"\\leftarrow",tag:"mo",output:"\u2190",ttype:CONST},{input:"\\to",tag:"mo",output:"\u2192",ttype:CONST},{input:"\\rightarrow",tag:"mo",output:"\u2192",ttype:CONST},{input:"\\leftrightarrow",tag:"mo",output:"\u2194",ttype:CONST},{input:"\\uparrow",tag:"mo",output:"\u2191",ttype:CONST},{input:"\\downarrow",tag:"mo",output:"\u2193",ttype:CONST},{input:"\\updownarrow",tag:"mo",output:"\u2195",ttype:CONST},{input:"\\Leftarrow",tag:"mo",output:"\u21D0",ttype:CONST},{input:"\\Rightarrow",tag:"mo",output:"\u21D2",ttype:CONST},{input:"\\Leftrightarrow",tag:"mo",output:"\u21D4",ttype:CONST},{input:"\\iff",tag:"mo",output:"~\\Longleftrightarrow~",ttype:DEFINITION},{input:"\\Uparrow",tag:"mo",output:"\u21D1",ttype:CONST},{input:"\\Downarrow",tag:"mo",output:"\u21D3",ttype:CONST},{input:"\\Updownarrow",tag:"mo",output:"\u21D5",ttype:CONST},{input:"\\mapsto",tag:"mo",output:"\u21A6",ttype:CONST},{input:"\\longleftarrow",tag:"mo",output:"\u2190",ttype:LONG},{input:"\\longrightarrow",tag:"mo",output:"\u2192",ttype:LONG},{input:"\\longleftrightarrow",tag:"mo",output:"\u2194",ttype:LONG},{input:"\\Longleftarrow",tag:"mo",output:"\u21D0",ttype:LONG},{input:"\\Longrightarrow",tag:"mo",output:"\u21D2",ttype:LONG},{input:"\\Longleftrightarrow",tag:"mo",output:"\u21D4",ttype:LONG},{input:"\\longmapsto",tag:"mo",output:"\u21A6",ttype:CONST},AMsqrt,AMroot,AMfrac,AMover,AMsub,AMsup,AMtext,AMmbox,AMatop,AMchoose,{input:"\\acute",tag:"mover",output:"\u00B4",ttype:UNARY,acc:true},{input:"\\grave",tag:"mover",output:"\u0060",ttype:UNARY,acc:true},{input:"\\breve",tag:"mover",output:"\u02D8",ttype:UNARY,acc:true},{input:"\\check",tag:"mover",output:"\u02C7",ttype:UNARY,acc:true},{input:"\\dot",tag:"mover",output:".",ttype:UNARY,acc:true},{input:"\\ddot",tag:"mover",output:"..",ttype:UNARY,acc:true},{input:"\\mathring",tag:"mover",output:"\u00B0",ttype:UNARY,acc:true},{input:"\\vec",tag:"mover",output:"\u20D7",ttype:UNARY,acc:true},{input:"\\overrightarrow",tag:"mover",output:"\u20D7",ttype:UNARY,acc:true},{input:"\\overleftarrow",tag:"mover",output:"\u20D6",ttype:UNARY,acc:true},{input:"\\hat",tag:"mover",output:"\u005E",ttype:UNARY,acc:true},{input:"\\widehat",tag:"mover",output:"\u0302",ttype:UNARY,acc:true},{input:"\\tilde",tag:"mover",output:"~",ttype:UNARY,acc:true},{input:"\\widetilde",tag:"mover",output:"\u02DC",ttype:UNARY,acc:true},{input:"\\bar",tag:"mover",output:"\u203E",ttype:UNARY,acc:true},{input:"\\overbrace",tag:"mover",output:"\uFE37",ttype:UNARY,acc:true},{input:"\\overbracket",tag:"mover",output:"\u23B4",ttype:UNARY,acc:true},{input:"\\overline",tag:"mover",output:"\u00AF",ttype:UNARY,acc:true},{input:"\\underbrace",tag:"munder",output:"\uFE38",ttype:UNARY,acc:true},{input:"\\underbracket",tag:"munder",output:"\u23B5",ttype:UNARY,acc:true},{input:"\\underline",tag:"munder",output:"\u00AF",ttype:UNARY,acc:true},{input:"\\displaystyle",tag:"mstyle",atname:"displaystyle",atval:"true",ttype:UNARY},{input:"\\textstyle",tag:"mstyle",atname:"displaystyle",atval:"false",ttype:UNARY},{input:"\\scriptstyle",tag:"mstyle",atname:"scriptlevel",atval:"1",ttype:UNARY},{input:"\\scriptscriptstyle",tag:"mstyle",atname:"scriptlevel",atval:"2",ttype:UNARY},{input:"\\textrm",tag:"mstyle",output:"\\mathrm",ttype:DEFINITION},{input:"\\mathbf",tag:"mstyle",atname:"mathvariant",atval:"bold",ttype:UNARY},{input:"\\textbf",tag:"mstyle",atname:"mathvariant",atval:"bold",ttype:UNARY},{input:"\\mathit",tag:"mstyle",atname:"mathvariant",atval:"italic",ttype:UNARY},{input:"\\textit",tag:"mstyle",atname:"mathvariant",atval:"italic",ttype:UNARY},{input:"\\mathtt",tag:"mstyle",atname:"mathvariant",atval:"monospace",ttype:UNARY},{input:"\\texttt",tag:"mstyle",atname:"mathvariant",atval:"monospace",ttype:UNARY},{input:"\\mathsf",tag:"mstyle",atname:"mathvariant",atval:"sans-serif",ttype:UNARY},{input:"\\mathbb",tag:"mstyle",atname:"mathvariant",atval:"double-struck",ttype:UNARY,codes:AMbbb},{input:"\\mathcal",tag:"mstyle",atname:"mathvariant",atval:"script",ttype:UNARY,codes:AMcal},{input:"\\mathfrak",tag:"mstyle",atname:"mathvariant",atval:"fraktur",ttype:UNARY,codes:AMfrk},{input:"\\textcolor",tag:"mstyle",atname:"mathvariant",atval:"mathcolor",ttype:BINARY},{input:"\\colorbox",tag:"mstyle",atname:"mathvariant",atval:"background",ttype:BINARY}];function compareNames(s1,s2){if(s1.input>s2.input)return 1
-  else return-1;}
-  var AMnames=[];function AMinitSymbols(){AMsymbols.sort(compareNames);for(i=0;i<AMsymbols.length;i++)AMnames[i]=AMsymbols[i].input;}
-  var AMmathml="http://www.w3.org/1998/Math/MathML";function AMcreateElementMathML(t){if(isIE)return document.createElement("m:"+t);else return document.createElementNS(AMmathml,t);}
-  function AMcreateMmlNode(t,frag){if(isIE)var node=document.createElement("m:"+t);else var node=document.createElementNS(AMmathml,t);node.appendChild(frag);return node;}
-  function newcommand(oldstr,newstr){AMsymbols=AMsymbols.concat([{input:oldstr,tag:"mo",output:newstr,ttype:DEFINITION}]);}
-  function AMremoveCharsAndBlanks(str,n){var st;st=str.slice(n);for(var i=0;i<st.length&&st.charCodeAt(i)<=32;i=i+1);return st.slice(i);}
-  function AMposition(arr,str,n){if(n==0){var h,m;n=-1;h=arr.length;while(n+1<h){m=(n+h)>>1;if(arr[m]<str)n=m;else h=m;}
-  return h;}else
-  for(var i=n;i<arr.length&&arr[i]<str;i++);return i;}
-  function AMgetSymbol(str){var k=0;var j=0;var mk;var st;var tagst;var match="";var more=true;for(var i=1;i<=str.length&&more;i++){st=str.slice(0,i);j=k;k=AMposition(AMnames,st,j);if(k<AMnames.length&&str.slice(0,AMnames[k].length)==AMnames[k]){match=AMnames[k];mk=k;i=match.length;}
-  more=k<AMnames.length&&str.slice(0,AMnames[k].length)>=AMnames[k];}
-  AMpreviousSymbol=AMcurrentSymbol;if(match!=""){AMcurrentSymbol=AMsymbols[mk].ttype;return AMsymbols[mk];}
-  AMcurrentSymbol=CONST;k=1;st=str.slice(0,1);if("0"<=st&&st<="9")tagst="mn";else tagst=(("A">st||st>"Z")&&("a">st||st>"z")?"mo":"mi");return{input:st,tag:tagst,output:st,ttype:CONST};}
-  var AMpreviousSymbol,AMcurrentSymbol;function AMparseSexpr(str){var symbol,node,result,result2,i,st,newFrag=document.createDocumentFragment();str=AMremoveCharsAndBlanks(str,0);symbol=AMgetSymbol(str);if(symbol==null||symbol.ttype==RIGHTBRACKET)
-  return[null,str,null];if(symbol.ttype==DEFINITION){str=symbol.output+AMremoveCharsAndBlanks(str,symbol.input.length);symbol=AMgetSymbol(str);if(symbol==null||symbol.ttype==RIGHTBRACKET)
-  return[null,str,null];}
-  str=AMremoveCharsAndBlanks(str,symbol.input.length);switch(symbol.ttype){case SPACE:node=AMcreateElementMathML(symbol.tag);node.setAttribute(symbol.atname,symbol.atval);return[node,str,symbol.tag];case UNDEROVER:if(isIE){if(symbol.input.substr(0,4)=="\\big"){str="\\"+symbol.input.substr(4)+str;symbol=AMgetSymbol(str);symbol.ttype=UNDEROVER;str=AMremoveCharsAndBlanks(str,symbol.input.length);}}
-  return[AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)),str,symbol.tag];case CONST:var output=symbol.output;if(isIE){if(symbol.input=="'")
-  output="\u2032";else if(symbol.input=="''")
-  output="\u2033";else if(symbol.input=="'''")
-  output="\u2033\u2032";else if(symbol.input=="''''")
-  output="\u2033\u2033";else if(symbol.input=="\\square")
-  output="\u25A1";else if(symbol.input.substr(0,5)=="\\frac"){var denom=symbol.input.substr(6,1);if(denom=="5"||denom=="6"){str=symbol.input.replace(/\\frac/,"\\frac ")+str;return[node,str,symbol.tag];}}}
-  node=AMcreateMmlNode(symbol.tag,document.createTextNode(output));return[node,str,symbol.tag];case LONG:node=AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output));node.setAttribute("minsize","1.5");node.setAttribute("maxsize","1.5");node=AMcreateMmlNode("mover",node);node.appendChild(AMcreateElementMathML("mspace"));return[node,str,symbol.tag];case STRETCHY:if(isIE&&symbol.input=="\\backslash")
-  symbol.output="\\";node=AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output));if(symbol.input=="|"||symbol.input=="\\vert"||symbol.input=="\\|"||symbol.input=="\\Vert"){node.setAttribute("lspace","0em");node.setAttribute("rspace","0em");}
-  node.setAttribute("maxsize",symbol.atval);if(symbol.rtag!=null)
-  return[node,str,symbol.rtag];else
-  return[node,str,symbol.tag];case BIG:var atval=symbol.atval;if(isIE)
-  atval=symbol.ieval;symbol=AMgetSymbol(str);if(symbol==null)
-  return[null,str,null];str=AMremoveCharsAndBlanks(str,symbol.input.length);node=AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output));if(isIE){var space=AMcreateElementMathML("mspace");space.setAttribute("height",atval+"ex");node=AMcreateMmlNode("mrow",node);node.appendChild(space);}else{node.setAttribute("minsize",atval);node.setAttribute("maxsize",atval);}
-  return[node,str,symbol.tag];case LEFTBRACKET:if(symbol.input=="\\left"){symbol=AMgetSymbol(str);if(symbol!=null){if(symbol.input==".")
-  symbol.invisible=true;str=AMremoveCharsAndBlanks(str,symbol.input.length);}}
-  result=AMparseExpr(str,true,false);if(symbol==null||(typeof symbol.invisible=="boolean"&&symbol.invisible))
-  node=AMcreateMmlNode("mrow",result[0]);else{node=AMcreateMmlNode("mo",document.createTextNode(symbol.output));node=AMcreateMmlNode("mrow",node);node.appendChild(result[0]);}
-  return[node,result[1],result[2]];case MATRIX:if(symbol.input=="\\begin{array}"){var mask="";symbol=AMgetSymbol(str);str=AMremoveCharsAndBlanks(str,0);if(symbol==null)
-  mask="l";else{str=AMremoveCharsAndBlanks(str,symbol.input.length);if(symbol.input!="{")
-  mask="l";else do{symbol=AMgetSymbol(str);if(symbol!=null){str=AMremoveCharsAndBlanks(str,symbol.input.length);if(symbol.input!="}")
-  mask=mask+symbol.input;}}while(symbol!=null&&symbol.input!=""&&symbol.input!="}");}
-  result=AMparseExpr("{"+str,true,true);node=AMcreateMmlNode("mtable",result[0]);mask=mask.replace(/l/g,"left ");mask=mask.replace(/r/g,"right ");mask=mask.replace(/c/g,"center ");node.setAttribute("columnalign",mask);node.setAttribute("displaystyle","false");if(isIE)
-  return[node,result[1],null];var lspace=AMcreateElementMathML("mspace");lspace.setAttribute("width","0.167em");var rspace=AMcreateElementMathML("mspace");rspace.setAttribute("width","0.167em");var node1=AMcreateMmlNode("mrow",lspace);node1.appendChild(node);node1.appendChild(rspace);return[node1,result[1],null];}else{result=AMparseExpr("{"+str,true,true);node=AMcreateMmlNode("mtable",result[0]);if(isIE)
-  node.setAttribute("columnspacing","0.25em");else
-  node.setAttribute("columnspacing","0.167em");node.setAttribute("columnalign","right center left");node.setAttribute("displaystyle","true");node=AMcreateMmlNode("mrow",node);return[node,result[1],null];}
-  case TEXT:if(str.charAt(0)=="{")i=str.indexOf("}");else i=0;if(i==-1)
-  i=str.length;st=str.slice(1,i);if(st.charAt(0)==" "){node=AMcreateElementMathML("mspace");node.setAttribute("width","0.33em");newFrag.appendChild(node);}
-  newFrag.appendChild(AMcreateMmlNode(symbol.tag,document.createTextNode(st)));if(st.charAt(st.length-1)==" "){node=AMcreateElementMathML("mspace");node.setAttribute("width","0.33em");newFrag.appendChild(node);}
-  str=AMremoveCharsAndBlanks(str,i+1);return[AMcreateMmlNode("mrow",newFrag),str,null];case UNARY:result=AMparseSexpr(str);if(result[0]==null)return[AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)),str];if(typeof symbol.func=="boolean"&&symbol.func){st=str.charAt(0);if(st=="^"||st=="_"||st==","){return[AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)),str,symbol.tag];}else{node=AMcreateMmlNode("mrow",AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)));if(isIE){var space=AMcreateElementMathML("mspace");space.setAttribute("width","0.167em");node.appendChild(space);}
-  node.appendChild(result[0]);return[node,result[1],symbol.tag];}}
-  if(symbol.input=="\\sqrt"){if(isIE){var space=AMcreateElementMathML("mspace");space.setAttribute("height","1.2ex");space.setAttribute("width","0em");node=AMcreateMmlNode(symbol.tag,result[0])
-  node.appendChild(space);return[node,result[1],symbol.tag];}else
-  return[AMcreateMmlNode(symbol.tag,result[0]),result[1],symbol.tag];}else if(typeof symbol.acc=="boolean"&&symbol.acc){node=AMcreateMmlNode(symbol.tag,result[0]);var output=symbol.output;if(isIE){if(symbol.input=="\\hat")
-  output="\u0302";else if(symbol.input=="\\widehat")
-  output="\u005E";else if(symbol.input=="\\bar")
-  output="\u00AF";else if(symbol.input=="\\grave")
-  output="\u0300";else if(symbol.input=="\\tilde")
-  output="\u0303";}
-  var node1=AMcreateMmlNode("mo",document.createTextNode(output));if(symbol.input=="\\vec"||symbol.input=="\\check")
-  node1.setAttribute("maxsize","1.2");if(isIE&&symbol.input=="\\bar")
-  node1.setAttribute("maxsize","0.5");if(symbol.input=="\\underbrace"||symbol.input=="\\underline")
-  node1.setAttribute("accentunder","true");else
-  node1.setAttribute("accent","true");node.appendChild(node1);if(symbol.input=="\\overbrace"||symbol.input=="\\underbrace")
-  node.ttype=UNDEROVER;return[node,result[1],symbol.tag];}else{if(!isIE&&typeof symbol.codes!="undefined"){for(i=0;i<result[0].childNodes.length;i++)
-  if(result[0].childNodes[i].nodeName=="mi"||result[0].nodeName=="mi"){st=(result[0].nodeName=="mi"?result[0].firstChild.nodeValue:result[0].childNodes[i].firstChild.nodeValue);var newst=[];for(var j=0;j<st.length;j++)
-  if(st.charCodeAt(j)>64&&st.charCodeAt(j)<91)newst=newst+
-  String.fromCharCode(symbol.codes[st.charCodeAt(j)-65]);else newst=newst+st.charAt(j);if(result[0].nodeName=="mi")
-  result[0]=AMcreateElementMathML("mo").appendChild(document.createTextNode(newst));else result[0].replaceChild(AMcreateElementMathML("mo").appendChild(document.createTextNode(newst)),result[0].childNodes[i]);}}
-  node=AMcreateMmlNode(symbol.tag,result[0]);node.setAttribute(symbol.atname,symbol.atval);if(symbol.input=="\\scriptstyle"||symbol.input=="\\scriptscriptstyle")
-  node.setAttribute("displaystyle","false");return[node,result[1],symbol.tag];}
-  case BINARY:result=AMparseSexpr(str);if(result[0]==null)return[AMcreateMmlNode("mo",document.createTextNode(symbol.input)),str,null];result2=AMparseSexpr(result[1]);if(result2[0]==null)return[AMcreateMmlNode("mo",document.createTextNode(symbol.input)),str,null];if(symbol.input=="\\textcolor"||symbol.input=="\\colorbox"){var tclr=str.match(/\{\s*([#\w]+)\s*\}/);str=str.replace(/\{\s*[#\w]+\s*\}/,"");if(tclr!=null){if(IsColorName.test(tclr[1].toLowerCase())){tclr=LaTeXColor[tclr[1].toLowerCase()];}else{tclr=tclr[1];}
-  node=AMcreateElementMathML("mstyle");node.setAttribute(symbol.atval,tclr);node.appendChild(result2[0]);return[node,result2[1],symbol.tag];}}
-  if(symbol.input=="\\root"||symbol.input=="\\stackrel")newFrag.appendChild(result2[0]);newFrag.appendChild(result[0]);if(symbol.input=="\\frac")newFrag.appendChild(result2[0]);return[AMcreateMmlNode(symbol.tag,newFrag),result2[1],symbol.tag];case INFIX:str=AMremoveCharsAndBlanks(str,symbol.input.length);return[AMcreateMmlNode("mo",document.createTextNode(symbol.output)),str,symbol.tag];default:return[AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)),str,symbol.tag];}}
-  function AMparseIexpr(str){var symbol,sym1,sym2,node,result,tag,underover;str=AMremoveCharsAndBlanks(str,0);sym1=AMgetSymbol(str);result=AMparseSexpr(str);node=result[0];str=result[1];tag=result[2];symbol=AMgetSymbol(str);if(symbol.ttype==INFIX){str=AMremoveCharsAndBlanks(str,symbol.input.length);result=AMparseSexpr(str);if(result[0]==null)
-  result[0]=AMcreateMmlNode("mo",document.createTextNode("\u25A1"));str=result[1];tag=result[2];if(symbol.input=="_"||symbol.input=="^"){sym2=AMgetSymbol(str);tag=null;underover=((sym1.ttype==UNDEROVER)||(node.ttype==UNDEROVER));if(symbol.input=="_"&&sym2.input=="^"){str=AMremoveCharsAndBlanks(str,sym2.input.length);var res2=AMparseSexpr(str);str=res2[1];tag=res2[2];node=AMcreateMmlNode((underover?"munderover":"msubsup"),node);node.appendChild(result[0]);node.appendChild(res2[0]);}else if(symbol.input=="_"){node=AMcreateMmlNode((underover?"munder":"msub"),node);node.appendChild(result[0]);}else{node=AMcreateMmlNode((underover?"mover":"msup"),node);node.appendChild(result[0]);}
-  node=AMcreateMmlNode("mrow",node);}else{node=AMcreateMmlNode(symbol.tag,node);if(symbol.input=="\\atop"||symbol.input=="\\choose")
-  node.setAttribute("linethickness","0ex");node.appendChild(result[0]);if(symbol.input=="\\choose")
-  node=AMcreateMmlNode("mfenced",node);}}
-  return[node,str,tag];}
-  function AMparseExpr(str,rightbracket,matrix){var symbol,node,result,i,tag,newFrag=document.createDocumentFragment();do{str=AMremoveCharsAndBlanks(str,0);result=AMparseIexpr(str);node=result[0];str=result[1];tag=result[2];symbol=AMgetSymbol(str);if(node!=undefined){if((tag=="mn"||tag=="mi")&&symbol!=null&&typeof symbol.func=="boolean"&&symbol.func){var space=AMcreateElementMathML("mspace");space.setAttribute("width","0.167em");node=AMcreateMmlNode("mrow",node);node.appendChild(space);}
-  newFrag.appendChild(node);}}while((symbol.ttype!=RIGHTBRACKET)&&symbol!=null&&symbol.output!="");tag=null;if(symbol.ttype==RIGHTBRACKET){if(symbol.input=="\\right"){str=AMremoveCharsAndBlanks(str,symbol.input.length);symbol=AMgetSymbol(str);if(symbol!=null&&symbol.input==".")
-  symbol.invisible=true;if(symbol!=null)
-  tag=symbol.rtag;}
-  if(symbol!=null)
-  str=AMremoveCharsAndBlanks(str,symbol.input.length);var len=newFrag.childNodes.length;if(matrix&&len>0&&newFrag.childNodes[len-1].nodeName=="mrow"&&len>1&&newFrag.childNodes[len-2].nodeName=="mo"&&newFrag.childNodes[len-2].firstChild.nodeValue=="&"){var pos=[];var m=newFrag.childNodes.length;for(i=0;matrix&&i<m;i=i+2){pos[i]=[];node=newFrag.childNodes[i];for(var j=0;j<node.childNodes.length;j++)
-  if(node.childNodes[j].firstChild.nodeValue=="&")
-  pos[i][pos[i].length]=j;}
-  var row,frag,n,k,table=document.createDocumentFragment();for(i=0;i<m;i=i+2){row=document.createDocumentFragment();frag=document.createDocumentFragment();node=newFrag.firstChild;n=node.childNodes.length;k=0;for(j=0;j<n;j++){if(typeof pos[i][k]!="undefined"&&j==pos[i][k]){node.removeChild(node.firstChild);row.appendChild(AMcreateMmlNode("mtd",frag));k++;}else frag.appendChild(node.firstChild);}
-  row.appendChild(AMcreateMmlNode("mtd",frag));if(newFrag.childNodes.length>2){newFrag.removeChild(newFrag.firstChild);newFrag.removeChild(newFrag.firstChild);}
-  table.appendChild(AMcreateMmlNode("mtr",row));}
-  return[table,str];}
-  if(typeof symbol.invisible!="boolean"||!symbol.invisible){node=AMcreateMmlNode("mo",document.createTextNode(symbol.output));newFrag.appendChild(node);}}
-  return[newFrag,str,tag];}
-  function AMparseMath(str){var result,node=AMcreateElementMathML("mstyle");var cclr=str.match(/\\color\s*\{\s*([#\w]+)\s*\}/);str=str.replace(/\\color\s*\{\s*[#\w]+\s*\}/g,"");if(cclr!=null){if(IsColorName.test(cclr[1].toLowerCase())){cclr=LaTeXColor[cclr[1].toLowerCase()];}else{cclr=cclr[1];}
-  node.setAttribute("mathcolor",cclr);}else{if(mathcolor!="")node.setAttribute("mathcolor",mathcolor);};if(mathfontfamily!="")node.setAttribute("fontfamily",mathfontfamily);node.appendChild(AMparseExpr(str.replace(/^\s+/g,""),false,false)[0]);node=AMcreateMmlNode("math",node);if(showasciiformulaonhover)
-  node.setAttribute("title",str.replace(/\s+/g," "));if(false){var fnode=AMcreateElementXHTML("font");fnode.setAttribute("face",mathfontfamily);fnode.appendChild(node);return fnode;}
-  return node;}
-  function AMstrarr2docFrag(arr,linebreaks){var newFrag=document.createDocumentFragment();var expr=false;for(var i=0;i<arr.length;i++){if(expr)newFrag.appendChild(AMparseMath(arr[i]));else{var arri=(linebreaks?arr[i].split("\n\n"):[arr[i]]);newFrag.appendChild(AMcreateElementXHTML("span").appendChild(document.createTextNode(arri[0])));for(var j=1;j<arri.length;j++){newFrag.appendChild(AMcreateElementXHTML("p"));newFrag.appendChild(AMcreateElementXHTML("span").appendChild(document.createTextNode(arri[j])));}}
-  expr=!expr;}
-  return newFrag;}
-  function AMprocessNodeR(n,linebreaks){var mtch,str,arr,frg,i;if(n.childNodes.length==0){if((n.nodeType!=8||linebreaks)&&n.parentNode.nodeName!="form"&&n.parentNode.nodeName!="FORM"&&n.parentNode.nodeName!="textarea"&&n.parentNode.nodeName!="TEXTAREA"&&n.parentNode.nodeName!="pre"&&n.parentNode.nodeName!="PRE"){str=n.nodeValue;if(!(str==null)){str=str.replace(/\r\n\r\n/g,"\n\n");str=str.replace(/\x20+/g," ");str=str.replace(/\s*\r\n/g," ");mtch=(str.indexOf("\$")==-1?false:true);str=str.replace(/([^\\])\$/g,"$1 \$");str=str.replace(/^\$/," \$");arr=str.split(" \$");for(i=0;i<arr.length;i++)
-  arr[i]=arr[i].replace(/\\\$/g,"\$");if(arr.length>1||mtch){if(checkForMathML){checkForMathML=false;var nd=AMisMathMLavailable();AMnoMathML=nd!=null;if(AMnoMathML&&notifyIfNoMathML)
-  if(alertIfNoMathML)
-  alert("To view the ASCIIMathML notation use Internet Explorer 6 +\nMathPlayer (free from www.dessci.com)\nor Firefox/Mozilla/Netscape");else AMbody.insertBefore(nd,AMbody.childNodes[0]);}
-  if(!AMnoMathML){frg=AMstrarr2docFrag(arr,n.nodeType==8);var len=frg.childNodes.length;n.parentNode.replaceChild(frg,n);return len-1;}else return 0;}}}else return 0;}else if(n.nodeName!="math"){for(i=0;i<n.childNodes.length;i++)
-  i+=AMprocessNodeR(n.childNodes[i],linebreaks);}
-  return 0;}
-  function AMprocessNode(n,linebreaks,spanclassAM){var frag,st;if(spanclassAM!=null){frag=document.getElementsByTagName("span")
-  for(var i=0;i<frag.length;i++)
-  if(frag[i].className=="AM")
-  AMprocessNodeR(frag[i],linebreaks);}else{try{st=n.innerHTML;}catch(err){}
-  if(st==null||st.indexOf("\$")!=-1)
-  AMprocessNodeR(n,linebreaks);}
-  if(isIE){frag=document.getElementsByTagName('math');for(var i=0;i<frag.length;i++)frag[i].update()}}
-  var inAppendix=false;var sectionCntr=0;var IEcommentWarning=true;var biblist=[];var bibcntr=0;var LaTeXCounter=[];LaTeXCounter["definition"]=0;LaTeXCounter["proposition"]=0;LaTeXCounter["lemma"]=0;LaTeXCounter["theorem"]=0;LaTeXCounter["corollary"]=0;LaTeXCounter["example"]=0;LaTeXCounter["exercise"]=0;LaTeXCounter["subsection"]=0;LaTeXCounter["subsubsection"]=0;LaTeXCounter["figure"]=0;LaTeXCounter["equation"]=0;LaTeXCounter["table"]=0;var LaTeXColor=[];LaTeXColor["greenyellow"]="#D9FF4F";LaTeXColor["yellow"]="#FFFF00";LaTeXColor["goldenrod"]="#FFE529";LaTeXColor["dandelion"]="#FFB529";LaTeXColor["apricot"]="#FFAD7A";LaTeXColor["peach"]="#FF804D";LaTeXColor["melon"]="#FF8A80";LaTeXColor["yelloworange"]="#FF9400";LaTeXColor["orange"]="#FF6321";LaTeXColor["burntorange"]="#FF7D00";LaTeXColor["bittersweet"]="#C20300";LaTeXColor["redorange"]="#FF3B21";LaTeXColor["mahogany"]="#A60000";LaTeXColor["maroon"]="#AD0000";LaTeXColor["brickred"]="#B80000";LaTeXColor["red"]="#FF0000";LaTeXColor["orangered"]="#FF0080";LaTeXColor["rubinered"]="#FF00DE";LaTeXColor["wildstrawberry"]="#FF0A9C";LaTeXColor["salmon"]="#FF789E";LaTeXColor["carnationpink"]="#FF5EFF";LaTeXColor["magenta"]="#FF00FF";LaTeXColor["violetred"]="#FF30FF";LaTeXColor["rhodamine"]="#FF2EFF";LaTeXColor["mulberry"]="#A314FA";LaTeXColor["redviolet"]="#9600A8";LaTeXColor["fuchsia"]="#7303EB";LaTeXColor["lavender"]="#FF85FF";LaTeXColor["thistle"]="#E069FF";LaTeXColor["orchid"]="#AD5CFF";LaTeXColor["darkorchid"]="#9933CC";LaTeXColor["purple"]="#8C24FF";LaTeXColor["plum"]="#8000FF";LaTeXColor["violet"]="#361FFF";LaTeXColor["royalpurple"]="#401AFF";LaTeXColor["blueviolet"]="#1A0DF5";LaTeXColor["periwinkle"]="#6E73FF";LaTeXColor["cadetblue"]="#616EC4";LaTeXColor["cornflowerblue"]="#59DEFF";LaTeXColor["midnightblue"]="#007091";LaTeXColor["navyblue"]="#0F75FF";LaTeXColor["royalblue"]="#0080FF";LaTeXColor["blue"]="#0000FF";LaTeXColor["cerulean"]="#0FE3FF";LaTeXColor["cyan"]="#00FFFF";LaTeXColor["processblue"]="#0AFFFF";LaTeXColor["skyblue"]="#61FFE0";LaTeXColor["turquoise"]="#26FFCC";LaTeXColor["tealblue"]="#1FFAA3";LaTeXColor["aquamarine"]="#2EFFB2";LaTeXColor["bluegreen"]="#26FFAB";LaTeXColor["emerald"]="#00FF80";LaTeXColor["junglegreen"]="#03FF7A";LaTeXColor["seagreen"]="#4FFF80";LaTeXColor["green"]="#00FF00";LaTeXColor["forestgreen"]="#00E000";LaTeXColor["pinegreen"]="#00BF29";LaTeXColor["limegreen"]="#80FF00";LaTeXColor["yellowgreen"]="#8FFF42";LaTeXColor["springgreen"]="#BDFF3D";LaTeXColor["olivegreen"]="#009900";LaTeXColor["rawsienna"]="#8C0000";LaTeXColor["sepia"]="#4D0000";LaTeXColor["brown"]="#660000";LaTeXColor["tan"]="#DB9470";LaTeXColor["gray"]="#808080";LaTeXColor["grey"]="#808080";LaTeXColor["black"]="#000000";LaTeXColor["white"]="#FFFFFF";var IsColorName=/^(?:greenyellow|yellow|goldenrod|dandelion|apricot|peach|melon|yelloworange|orange|burntorange|bittersweet|redorange|mahogany|maroon|brickred|red|orangered|rubinered|wildstrawberry|salmon|carnationpink|magenta|violetred|rhodamine|mulberry|redviolet|fuchsia|lavender|thistle|orchid|darkorchid|purple|plum|violet|royalpurple|blueviolet|periwinkle|cadetblue|cornflowerblue|midnightblue|navyblue|royalblue|blue|cerulean|cyan|processblue|skyblue|turquoise|tealblue|aquamarine|bluegreen|emerald|junglegreen|seagreen|green|forestgreen|pinegreen|limegreen|yellowgreen|springgreen|olivegreen|rawsienna|sepia|brown|tan|gray|grey|black|white)$/;var IsCounter=/^(?:definition|proposition|lemma|theorem|corollary|example|exercise|subsection|subsubsection|figure|equation|table)$/;var IsLaTeXElement=/^(?:displayequation|title|author|address|date|abstract|keyword|section|subsection|subsubsection|ref|cite|thebibliography|definition|proposition|lemma|theorem|corollary|example|exercise|itemize|enumerate|enddefinition|endproposition|endlemma|endtheorem|endcorollary|endexample|endexercise|enditemize|endenumerate|LaTeXMathMLlabel|LaTeXMathML|smallskip|medskip|bigskip|quote|quotation|endquote|endquotation|center|endcenter|description|enddescription|inlinemath)$/;var IsTextOnlyArea=/^(?:form|textarea|pre)$/i;var tableid=0;function makeNumberString(cntr){if(sectionCntr>0){if(inAppendix){return"A"+sectionCntr+"."+cntr;}else{return sectionCntr+"."+cntr;}}else{return""+cntr;}};function LaTeXpreProcess(thebody){var TheBody=thebody;if(TheBody.hasChildNodes()){if(!(IsLaTeXElement.test(TheBody.className)))
-  {for(var i=0;i<TheBody.childNodes.length;i++){LaTeXpreProcess(TheBody.childNodes[i])}}}
-  else{if(TheBody.nodeType==3&&!(IsTextOnlyArea.test(TheBody.parentNode.nodeName)))
-  {var str=TheBody.nodeValue;if(!(str==null)){str=str.replace(/\\%/g,"<per>");str=str.replace(/%[^\n]*(?=\n)/g,"");str=str.replace(/%[^\r]*(?=\r)/g,"");str=str.replace(/%[^\n]*$/,"")
-  if(isIE&&str.match(/%/g)!=null&&IEcommentWarning){alert("Comments may not have parsed properly.  Try putting in <pre class='LaTeX><div>..</div></pre> structure.");IEcommentWarning=false;}
-  str=str.replace(/<per>/g,"%");if(str.match(/XXX[\s\S]*/)!=null){var tmp=str.match(/XXX[\s\S]*/)[0];var tmpstr=tmp.charCodeAt(7)+"::"+tmp.charCodeAt(8)+"::"+tmp.charCodeAt(9)+"::"+tmp.charCodeAt(10)+"::"+tmp.charCodeAt(11)+"::"+tmp.charCodeAt(12)+"::"+tmp.charCodeAt(13);alert(tmpstr);}
-  str=str.replace(/([^\\])\\(\s)/g,"$1\u00A0$2");str=str.replace(/\\quad/g,"\u2001");str=str.replace(/\\qquad/g,"\u2001\u2001");str=str.replace(/\\enspace/g,"\u2002");str=str.replace(/\\;/g,"\u2004");str=str.replace(/\\:/g,"\u2005");str=str.replace(/\\,/g,"\u2006");str=str.replace(/\\thinspace/g,"\u200A");str=str.replace(/([^\\])~/g,"$1\u00A0");str=str.replace(/\\~/g,"~");str=str.replace(/\\\[/g," <DEQ> $\\displaystyle{");str=str.replace(/\\\]/g,"}$ <DEQ> ");str=str.replace(/\$\$/g,"${$<DEQ>$}$");str=str.replace(/\\begin\s*\{\s*array\s*\}/g,"\\begin{array}");str=str.replace(/\\end\s*\{\s*array\s*\}/g,"\\end{array}");str=str.replace(/\\begin\s*\{\s*eqnarray\s*\}/g,"  <DEQ>eqno$\\begin{eqnarray}");str=str.replace(/\\end\s*\{\s*eqnarray\s*\}/g,"\\end{eqnarray}$<DEQ>  ");str=str.replace(/\\begin\s*\{\s*eqnarray\*\s*\}/g,"  <DEQ>$\\begin{eqnarray}");str=str.replace(/\\end\s*\{\s*eqnarray\*\s*\}/g,"\\end{eqnarray}$<DEQ>  ");str=str.replace(/\\begin\s*\{\s*displaymath\s*\}/g," <DEQ> $\\displaystyle{");str=str.replace(/\\end\s*\{\s*displaymath\s*\}/g,"}$ <DEQ> ");str=str.replace(/\\begin\s*\{\s*equation\s*\*\s*\}/g," <DEQ> $\\displaystyle{");str=str.replace(/\\end\s*\{\s*equation\s*\*\s*\}/g,"}$ <DEQ> ");str=str.replace(/\\begin\s*\{\s*equation\s*\}/g," <DEQ>eqno$\\displaystyle{");str=str.replace(/\\end\s*\{\s*equation\s*\}/g,"}$ <DEQ> ");str=str.split("<DEQ>");var newFrag=document.createDocumentFragment();for(var i=0;i<str.length;i++){if(i%2){var DEQtable=document.createElement("table");DEQtable.className='displayequation';var DEQtbody=document.createElement("tbody");var DEQtr=document.createElement("tr");var DEQtdeq=document.createElement("td");DEQtdeq.className='eq';str[i]=str[i].replace(/\$\}\$/g,"$\\displaystyle{");str[i]=str[i].replace(/\$\{\$/g,"}");var lbl=str[i].match(/\\label\s*\{\s*(\w+)\s*\}/);var ISeqno=str[i].match(/^eqno/);str[i]=str[i].replace(/^eqno/," ");str[i]=str[i].replace(/\\label\s*\{\s*\w+\s*\}/," ");DEQtdeq.appendChild(document.createTextNode(str[i]));DEQtr.appendChild(DEQtdeq);str[i]=str[i].replace(/\\nonumber/g,"");if(ISeqno!=null||lbl!=null){var DEQtdno=document.createElement("td");DEQtdno.className='eqno';LaTeXCounter["equation"]++;var eqnoString=makeNumberString(LaTeXCounter["equation"]);var DEQanchor=document.createElement("a");if(lbl!=null){DEQanchor.id=lbl[1]};DEQanchor.className="eqno";var anchorSpan=document.createElement("span");anchorSpan.className="eqno";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(eqnoString));DEQanchor.appendChild(anchorSpan);DEQtdno.appendChild(DEQanchor);var DEQspan=document.createElement("span");DEQspan.className="eqno";DEQspan.appendChild(document.createTextNode("("+eqnoString+")"));DEQtdno.appendChild(DEQspan);DEQtr.appendChild(DEQtdno);}
-  DEQtbody.appendChild(DEQtr);DEQtable.appendChild(DEQtbody);newFrag.appendChild(DEQtable);}
-  else{str[i]=str[i].replace(/\$\}\$/g,"");str[i]=str[i].replace(/\$\{\$/g,"");str[i]=str[i].replace(/\\maketitle/g,"");str[i]=str[i].replace(/\\begin\s*\{\s*document\s*\}/g,"");str[i]=str[i].replace(/\\end\s*\{\s*document\s*\}/g,"");str[i]=str[i].replace(/\\documentclass[^\}]*?\}/g,"");str[i]=str[i].replace(/\\usepackage[^\}]*?\}/g,"");str[i]=str[i].replace(/\\noindent/g,"");str[i]=str[i].replace(/\\notag/g,"");str[i]=str[i].replace(/\\ref\s*\{\s*(\w+)\}/g," \\[ref\\]$1\\[ ");str[i]=str[i].replace(/\\url\s*\{\s*([^\}\n]+)\}/g," \\[url\\]$1\\[ ");str[i]=str[i].replace(/\\href\s*\{\s*([^\}]+)\}\s*\{\s*([^\}]+)\}/g," \\[href\\]$1\\]$2\\[ ");str[i]=str[i].replace(/\\cite\s*\{\s*(\w+)\}/g," \\[cite\\]$1\\[ ");str[i]=str[i].replace(/\\qed/g,"\u220E");str[i]=str[i].replace(/\\endproof/g,"\u220E");str[i]=str[i].replace(/\\proof/g,"\\textbf{Proof: }");str[i]=str[i].replace(/\\n(?=\s)/g," \\[br\\] \\[ ");str[i]=str[i].replace(/\\newline/g," \\[br\\] \\[ ");str[i]=str[i].replace(/\\linebreak/g," \\[br\\] \\[ ");str[i]=str[i].replace(/\\smallskip/g," \\[logicalbreak\\]smallskip\\[ ");str[i]=str[i].replace(/\\medskip/g," \\[logicalbreak\\]medskip\\[ ");str[i]=str[i].replace(/\\bigskip/g," \\[logicalbreak\\]bigskip\\[ ");str[i]=str[i].replace(/[\n\r]+[ \f\n\r\t\v\u2028\u2029]*[\n\r]+/g," \\[logicalbreak\\]LaTeXMathML\\[ ");if(isIE){str[i]=str[i].replace(/\r/g," ");}
-  str[i]=str[i].replace(/\\bibitem\s*([^\{]*\{\s*\w*\s*\})/g," \\[bibitem\\]$1\\[ ");str[i]=str[i].replace(/\\bibitem\s*/g," \\[bibitem\\] \\[ ");str[i]=str[i].replace(/\\item\s*\[\s*(\w+)\s*\]/g," \\[alistitem\\]$1\\[ ");str[i]=str[i].replace(/\\item\s*/g," \\[alistitem\\] \\[ ");str[i]=str[i].replace(/\\appendix/g," \\[appendix\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*figure\s*\}([\s\S]+?)\\end\s*\{\s*figure\s*\}/g," \\[figure\\]$1\\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*table\s*\}([\s\S]+?)\\end\s*\{\s*table\s*\}/g," \\[table\\]$1\\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*theorem\s*\}/g," \\[theorem\\]Theorem \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*theorem\s*\}/g," \\[endtheorem\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*definition\s*\}/g," \\[definition\\]Definition \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*definition\s*\}/g," \\[enddefinition\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*lemma\s*\}/g," \\[lemma\\]Lemma \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*lemma\s*\}/g," \\[endlemma\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*corollary\s*\}/g," \\[corollary\\]Corollary \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*corollary\s*\}/g," \\[endcorollary\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*proposition\s*\}/g," \\[proposition\\]Proposition \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*proposition\s*\}/g," \\[endproposition\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*example\s*\}/g," \\[example\\]Example \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*example\s*\}/g," \\[endexample\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*exercise\s*\}/g," \\[exercise\\]Exercise \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*exercise\s*\}/g," \\[endexercise\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*thebibliography\s*\}\s*\{\s*\w+\s*\}/g," \\[thebibliography\\]References \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*thebibliography\s*\}/g," \\[thebibliography\\]References \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*thebibliography\s*\}/g," \\[endthebibliography\\]References \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*proof\s*\}/g," \\[proof\\]Proof: \\[ ");if(isIE){str[i]=str[i].replace(/\\end\s*\{\s*proof\s*\}/g,"\u220E \\[endproof\\] \\[ ");}else{str[i]=str[i].replace(/\\end\s*\{\s*proof\s*\}/g," \\[endproof\\] \\[ ");}
-  str[i]=str[i].replace(/\\title\s*\{\s*([^\}]+)\}/g," \\[title\\] \\[$1 \\[endtitle\\] \\[ ");str[i]=str[i].replace(/\\author\s*\{\s*([^\}]+)\}/g," \\[author\\] \\[$1 \\[endauthor\\] \\[ ");str[i]=str[i].replace(/\\address\s*\{\s*([^\}]+)\}/g," \\[address\\] \\[$1 \\[endaddress\\] \\[ ");str[i]=str[i].replace(/\\date\s*\{\s*([^\}]+)\}/g," \\[date\\] \\[$1 \\[enddate\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*keyword\s*\}/g," \\[keyword\\] \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*keyword\s*\}/g," \\[endkeyword\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*abstract\s*\}/g," \\[abstract\\] \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*abstract\s*\}/g," \\[endabstract\\] \\[ ");str[i]=str[i].replace(/\\begin\s*\{\s*(?!array|tabular)(\w+)\s*\}/g," \\[$1\\] \\[ ");str[i]=str[i].replace(/\\end\s*\{\s*(?!array|tabular)(\w+)\s*\}/g," \\[end$1\\] \\[ ");var sectionIndex=str[i].search(/\\section\s*\{\s*[\s\S]+\}/);while(sectionIndex>=0){str[i]=str[i].replace(/\\section\s*\{/," \\[section\\]");var delimcnt=1;for(var ii=sectionIndex;ii<str[i].length;ii++){if(str[i].charAt(ii)=="{"){delimcnt++};if(str[i].charAt(ii)=="}"){delimcnt--};if(delimcnt==0){str[i]=str[i].substring(0,ii)+"\\[ "+str[i].substring(ii+1,str[i].length);break;}};sectionIndex=str[i].search(/\\section\s*\{\s*[\s\S]+\}/);}
-  sectionIndex=str[i].search(/\\subsection\s*\{\s*[\s\S]+\}/);while(sectionIndex>=0){str[i]=str[i].replace(/\\subsection\s*\{/," \\[subsection\\]");var delimcnt=1;for(var ii=sectionIndex;ii<str[i].length;ii++){if(str[i].charAt(ii)=="{"){delimcnt++};if(str[i].charAt(ii)=="}"){delimcnt--};if(delimcnt==0){str[i]=str[i].substring(0,ii)+"\\[ "+str[i].substring(ii+1,str[i].length);break;}};sectionIndex=str[i].search(/\\subsection\s*\{\s*[\s\S]+\}/);}
-  sectionIndex=str[i].search(/\\subsubsection\s*\{\s*[\s\S]+\}/);while(sectionIndex>=0){str[i]=str[i].replace(/\\subsubsection\s*\{/," \\[subsubsection\\]");var delimcnt=1;for(var ii=sectionIndex;ii<str[i].length;ii++){if(str[i].charAt(ii)=="{"){delimcnt++};if(str[i].charAt(ii)=="}"){delimcnt--};if(delimcnt==0){str[i]=str[i].substring(0,ii)+"\\[ "+str[i].substring(ii+1,str[i].length);break;}};sectionIndex=str[i].search(/\\subsubsection\s*\{\s*[\s\S]+\}/);}
-  var CatToNextEven="";var strtmp=str[i].split("\\[");for(var j=0;j<strtmp.length;j++){if(j%2){var strtmparray=strtmp[j].split("\\]");switch(strtmparray[0]){case"section":var nodeTmp=document.createElement("H2");nodeTmp.className='section';sectionCntr++;for(var div in LaTeXCounter){LaTeXCounter[div]=0};var nodeAnchor=document.createElement("a");if(inAppendix){nodeAnchor.className='appendixsection';}else{nodeAnchor.className='section';}
-  var nodeNumString=makeNumberString("");var anchorSpan=document.createElement("span");anchorSpan.className="section";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(nodeNumString));nodeAnchor.appendChild(anchorSpan);nodeTmp.appendChild(nodeAnchor);var nodeSpan=document.createElement("span");nodeSpan.className='section';nodeSpan.appendChild(document.createTextNode(nodeNumString+" "));nodeTmp.appendChild(nodeSpan);nodeTmp.appendChild(document.createTextNode(strtmparray[1]));newFrag.appendChild(nodeTmp);break;case"subsection":var nodeTmp=document.createElement("H3");nodeTmp.className='subsection';LaTeXCounter["subsection"]++;LaTeXCounter["subsubsection"]=0;var nodeAnchor=document.createElement("a");nodeAnchor.className='subsection';var nodeNumString=makeNumberString(LaTeXCounter["subsection"]);var anchorSpan=document.createElement("span");anchorSpan.className="subsection";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(nodeNumString));nodeAnchor.appendChild(anchorSpan);nodeTmp.appendChild(nodeAnchor);var nodeSpan=document.createElement("span");nodeSpan.className='subsection';nodeSpan.appendChild(document.createTextNode(nodeNumString+". "));nodeTmp.appendChild(nodeSpan);nodeTmp.appendChild(document.createTextNode(strtmparray[1]));newFrag.appendChild(nodeTmp);break;case"subsubsection":var nodeTmp=document.createElement("H4");nodeTmp.className='subsubsection';LaTeXCounter["subsubsection"]++;var nodeAnchor=document.createElement("a");nodeAnchor.className='subsubsection';var nodeNumString=makeNumberString(LaTeXCounter["subsection"]+"."+LaTeXCounter["subsubsection"]);var anchorSpan=document.createElement("span");anchorSpan.className="subsubsection";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(nodeNumString));nodeAnchor.appendChild(anchorSpan);nodeTmp.appendChild(nodeAnchor);var nodeSpan=document.createElement("span");nodeSpan.className='subsubsection';nodeSpan.appendChild(document.createTextNode(nodeNumString+". "));nodeTmp.appendChild(nodeSpan);nodeTmp.appendChild(document.createTextNode(strtmparray[1]));newFrag.appendChild(nodeTmp);break;case"href":var nodeTmp=document.createElement("a");nodeTmp.className='LaTeXMathML';nodeTmp.href=strtmparray[1];nodeTmp.appendChild(document.createTextNode(strtmparray[2]));newFrag.appendChild(nodeTmp);break;case"url":var nodeTmp=document.createElement("a");nodeTmp.className='LaTeXMathML';nodeTmp.href=strtmparray[1];nodeTmp.appendChild(document.createTextNode(strtmparray[1]));newFrag.appendChild(nodeTmp);break;case"figure":var nodeTmp=document.createElement("table");nodeTmp.className='figure';var FIGtbody=document.createElement("tbody");var FIGlbl=strtmparray[1].match(/\\label\s*\{\s*(\w+)\s*\}/);strtmparray[1]=strtmparray[1].replace(/\\label\s*\{\w+\}/g,"");var capIndex=strtmparray[1].search(/\\caption\s*\{[\s\S]+\}/);var FIGcap="";if(capIndex>=0){var tmp=strtmparray[1];var delimcnt=0;var capstart=-1;for(var pos=capIndex;pos<tmp.length;pos++){if(tmp.charAt(pos)=="{"){delimcnt++};if(tmp.charAt(pos)=="}"){delimcnt--};if(delimcnt==1&&capstart<0){capstart=pos+1};if(delimcnt==0&&capstart>0){capend=pos-1;FIGcap=tmp.substring(capstart,pos);break}}}
-  var FIGtr2=document.createElement("tr");var FIGtd2=document.createElement("td");FIGtd2.className="caption";var FIGanchor=document.createElement("a");FIGanchor.className="figure";if(FIGlbl!=null){FIGanchor.id=FIGlbl[1];}
-  LaTeXCounter["figure"]++;var fignmbr=makeNumberString(LaTeXCounter["figure"]);var anchorSpan=document.createElement("span");anchorSpan.className="figure";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(fignmbr));FIGanchor.appendChild(anchorSpan);FIGtd2.appendChild(FIGanchor);var FIGspan=document.createElement("span");FIGspan.className="figure";FIGspan.appendChild(document.createTextNode("Figure "+fignmbr+". "));FIGtd2.appendChild(FIGspan);FIGtd2.appendChild(document.createTextNode(""+FIGcap));FIGtr2.appendChild(FIGtd2);FIGtbody.appendChild(FIGtr2);var IsSpecial=false;var FIGinfo=strtmparray[1].match(/\\includegraphics\s*\{([^\}]+)\}/);if(FIGinfo==null){FIGinfo=strtmparray[1].match(/\\includegraphics\s*\[[^\]]*\]\s*\{\s*([^\}]+)\s*\}/);}
-  if(FIGinfo==null){FIGinfo=strtmparray[1].match(/\\special\s*\{\s*([^\}]+)\}/);IsSpecial=true};if(FIGinfo!=null){var FIGtr1=document.createElement("tr");var FIGtd1=document.createElement("td");FIGtd1.className="image";var FIGimg=document.createElement("img");var FIGsrc=FIGinfo[1];FIGimg.src=FIGsrc;FIGimg.alt="Figure "+FIGsrc+" did not load";FIGimg.title="Figure "+fignmbr+". "+FIGcap;FIGimg.id="figure"+fignmbr;FIGtd1.appendChild(FIGimg);FIGtr1.appendChild(FIGtd1);FIGtbody.appendChild(FIGtr1);}
-  nodeTmp.appendChild(FIGtbody);newFrag.appendChild(nodeTmp);break;case"table":var nodeTmp=document.createElement("table");if(strtmparray[1].search(/\\centering/)>=0){nodeTmp.className='LaTeXtable centered';nodeTmp.align="center";}else{nodeTmp.className='LaTeXtable';};tableid++;nodeTmp.id="LaTeXtable"+tableid;var TABlbl=strtmparray[1].match(/\\label\s*\{\s*(\w+)\s*\}/);strtmparray[1]=strtmparray[1].replace(/\\label\s*\{\w+\}/g,"");var capIndex=strtmparray[1].search(/\\caption\s*\{[\s\S]+\}/);var TABcap="";if(capIndex>=0){var tmp=strtmparray[1];var delimcnt=0;var capstart=-1;for(var pos=capIndex;pos<tmp.length;pos++){if(tmp.charAt(pos)=="{"){delimcnt++};if(tmp.charAt(pos)=="}"){delimcnt--};if(delimcnt==1&&capstart<0){capstart=pos+1};if(delimcnt==0&&capstart>0){capend=pos-1;TABcap=tmp.substring(capstart,pos);break}}}
-  if(TABcap!=""){var TABtbody=document.createElement("tbody");var TABcaption=document.createElement("caption");TABcaption.className="LaTeXtable centered";var TABanchor=document.createElement("a");TABanchor.className="LaTeXtable";if(TABlbl!=null){TABanchor.id=TABlbl[1];}
-  LaTeXCounter["table"]++;var tabnmbr=makeNumberString(LaTeXCounter["table"]);var anchorSpan=document.createElement("span");anchorSpan.className="LaTeXtable";anchorSpan.style.display="none";anchorSpan.appendChild(document.createTextNode(tabnmbr));TABanchor.appendChild(anchorSpan);TABcaption.appendChild(TABanchor);var TABspan=document.createElement("span");TABspan.className="LaTeXtable";TABspan.appendChild(document.createTextNode("Table "+tabnmbr+". "));TABcaption.appendChild(TABspan);TABcaption.appendChild(document.createTextNode(""+TABcap));nodeTmp.appendChild(TABcaption);}
-  var TABinfo=strtmparray[1].match(/\\begin\s*\{\s*tabular\s*\}([\s\S]+)\\end\s*\{\s*tabular\s*\}/);if(TABinfo!=null){var TABtbody=document.createElement('tbody');var TABrow=null;var TABcell=null;var row=0;var col=0;var TABalign=TABinfo[1].match(/^\s*\{([^\}]+)\}/);TABinfo=TABinfo[1].replace(/^\s*\{[^\}]+\}/,"");TABinfo=TABinfo.replace(/\\hline/g,"");TABalign[1]=TABalign[1].replace(/\|/g,"");TABalign[1]=TABalign[1].replace(/\s/g,"");TABinfo=TABinfo.split("\\\\");for(row=0;row<TABinfo.length;row++){TABrow=document.createElement("tr");TABinfo[row]=TABinfo[row].split("&");for(col=0;col<TABinfo[row].length;col++){TABcell=document.createElement("td");switch(TABalign[1].charAt(col)){case"l":TABcell.align="left";break;case"c":TABcell.align="center";break;case"r":TABcell.align="right";break;default:TABcell.align="left";};TABcell.appendChild(document.createTextNode(TABinfo[row][col]));TABrow.appendChild(TABcell);}
-  TABtbody.appendChild(TABrow);}
-  nodeTmp.appendChild(TABtbody);}
-  newFrag.appendChild(nodeTmp);break;case"logicalbreak":var nodeTmp=document.createElement("p");nodeTmp.className=strtmparray[1];nodeTmp.appendChild(document.createTextNode("\u00A0"));newFrag.appendChild(nodeTmp);break;case"appendix":inAppendix=true;sectionCntr=0;break;case"alistitem":var EndDiv=document.createElement("div");EndDiv.className="endlistitem";newFrag.appendChild(EndDiv);var BegDiv=document.createElement("div");BegDiv.className="listitem";if(strtmparray[1]!=" "){var BegSpan=document.createElement("span");BegSpan.className="listitemmarker";var boldBegSpan=document.createElement("b");boldBegSpan.appendChild(document.createTextNode(strtmparray[1]+" "));BegSpan.appendChild(boldBegSpan);BegDiv.appendChild(BegSpan);}
-  newFrag.appendChild(BegDiv);break;case"br":newFrag.appendChild(document.createElement("br"));break;case"bibitem":newFrag.appendChild(document.createElement("br"));var nodeTmp=document.createElement("a");nodeTmp.className='bibitem';var nodeSpan=document.createElement("span");nodeSpan.className='bibitem';bibcntr++;var lbl=strtmparray[1].match(/\{\s*(\w+)\s*\}/);strtmparray[1]=strtmparray[1].replace(/\s*\{\s*\w+\s*\}/g,"");strtmparray[1]=strtmparray[1].replace(/^\s*\[/,"");strtmparray[1]=strtmparray[1].replace(/\s*\]$/,"");strtmparray[1]=strtmparray[1].replace(/^\s+|\s+$/g,"");if(lbl==null){biblist[bibcntr]="bibitem"+bibcntr}else{biblist[bibcntr]=lbl[1];};nodeTmp.name=biblist[bibcntr];nodeTmp.id=biblist[bibcntr];if(strtmparray[1]!=""){nodeSpan.appendChild(document.createTextNode(strtmparray[1]));}else{nodeSpan.appendChild(document.createTextNode("["+bibcntr+"]"));}
-  nodeTmp.appendChild(nodeSpan);newFrag.appendChild(nodeTmp);break;case"cite":var nodeTmp=document.createElement("a");nodeTmp.className='cite';nodeTmp.name='cite';nodeTmp.href="#"+strtmparray[1];newFrag.appendChild(nodeTmp);break;case"ref":var nodeTmp=document.createElement("a");nodeTmp.className='ref';nodeTmp.name='ref';nodeTmp.href="#"+strtmparray[1];newFrag.appendChild(nodeTmp);break;default:var nodeTmp=document.createElement("div");nodeTmp.className=strtmparray[0];if(IsCounter.test(strtmparray[0])){LaTeXCounter[strtmparray[0]]++;var nodeAnchor=document.createElement("a");nodeAnchor.className=strtmparray[0];var divnum=makeNumberString(LaTeXCounter[strtmparray[0]]);var anchorSpan=document.createElement("span");anchorSpan.className=strtmparray[0];anchorSpan.appendChild(document.createTextNode(divnum));anchorSpan.style.display="none";nodeAnchor.appendChild(anchorSpan);nodeTmp.appendChild(nodeAnchor);var nodeSpan=document.createElement("span");nodeSpan.className=strtmparray[0];nodeSpan.appendChild(document.createTextNode(strtmparray[1]+" "+divnum+". "));nodeTmp.appendChild(nodeSpan);}
-  if(isIE){if(strtmparray[0]==("thebibliography"||"abstract"||"keyword"||"proof")){var nodeSpan=document.createElement("span");nodeSpan.className=strtmparray[0];nodeSpan.appendChild(document.createTextNode(strtmparray[1]));nodeTmp.appendChild(nodeSpan);}}
-  if(strtmparray[0]=="endenumerate"||strtmparray[0]=="enditemize"||strtmparray[0]=="enddescription"){var endDiv=document.createElement("div");endDiv.className="endlistitem";newFrag.appendChild(endDiv);}
-  newFrag.appendChild(nodeTmp);if(strtmparray[0]=="enumerate"||strtmparray[0]=="itemize"||strtmparray[0]=="description"){var endDiv=document.createElement("div");endDiv.className="listitem";newFrag.appendChild(endDiv);}}}else{strtmp[j]=strtmp[j].replace(/\\\$/g,"<per>");strtmp[j]=strtmp[j].replace(/\$([^\$]+)\$/g," \\[$1\\[ ");strtmp[j]=strtmp[j].replace(/<per>/g,"\\$");strtmp[j]=strtmp[j].replace(/\\begin\s*\{\s*math\s*\}([\s\S]+?)\\end\s*\{\s*math\s*\}/g," \\[$1\\[ ");var strtmptmp=strtmp[j].split("\\[");for(var jjj=0;jjj<strtmptmp.length;jjj++){if(jjj%2){var nodeTmp=document.createElement("span");nodeTmp.className='inlinemath';nodeTmp.appendChild(document.createTextNode("$"+strtmptmp[jjj]+"$"));newFrag.appendChild(nodeTmp);}else{var TagIndex=strtmptmp[jjj].search(/\\\w+/);var tmpIndex=TagIndex;while(tmpIndex>-1){if(/^\\textcolor/.test(strtmptmp[jjj].substring(TagIndex,strtmptmp[jjj].length))){strtmptmp[jjj]=strtmptmp[jjj].replace(/\\textcolor\s*\{\s*(\w+)\s*\}\s*/," \\[textcolor\\]$1\\]|");}else{if(/^\\colorbox/.test(strtmptmp[jjj].substring(TagIndex,strtmptmp[jjj].length))){strtmptmp[jjj]=strtmptmp[jjj].replace(/\\colorbox\s*\{\s*(\w+)\s*\}\s*/," \\[colorbox\\]$1\\]|");}else{strtmptmp[jjj]=strtmptmp[jjj].substring(0,TagIndex)+strtmptmp[jjj].substring(TagIndex,strtmptmp[jjj].length).replace(/\\\s*(\w+)\s*/," \\[$1\\]|");}}
-  TagIndex+=strtmptmp[jjj].substring(TagIndex,strtmptmp[jjj].length).search(/\|/);TagIndex++;strtmptmp[jjj]=strtmptmp[jjj].replace(/\\\]\|/,"\\] ");if(strtmptmp[jjj].charAt(TagIndex)=="{"){strtmptmp[jjj]=strtmptmp[jjj].substring(0,TagIndex)+strtmptmp[jjj].substring(TagIndex+1,strtmptmp[jjj].length);var delimcnt=1;for(var kk=TagIndex;kk<strtmptmp[jjj].length;kk++){if(strtmptmp[jjj].charAt(kk)=="{"){delimcnt++};if(strtmptmp[jjj].charAt(kk)=="}"){delimcnt--};if(delimcnt==0){break;}}
-  strtmptmp[jjj]=strtmptmp[jjj].substring(0,kk)+"\\[ "+strtmptmp[jjj].substring(kk+1,strtmptmp[jjj].length);TagIndex=kk+3;}else{strtmptmp[jjj]=strtmptmp[jjj].substring(0,TagIndex)+"\\[ "+strtmptmp[jjj].substring(TagIndex+1,strtmptmp[jjj].length);TagIndex=TagIndex+3;}
-  if(TagIndex<strtmptmp[jjj].length){tmpIndex=strtmptmp[jjj].substring(TagIndex,strtmptmp[jjj].length).search(/\\\w+/);}
-  else{tmpIndex=-1};TagIndex+=tmpIndex;}
-  strtmptmp[jjj]=strtmptmp[jjj].replace(/\\\\\s*\\\\/g,"\\\\");strtmptmp[jjj]=strtmptmp[jjj].replace(/\\\\/g," \\[br\\] \\[ ");strtmptmp[jjj]=strtmptmp[jjj].replace(/\\label\s*\{\s*(\w+)\s*\}/g," \\[a\\]$1\\[ ");var strlbls=strtmptmp[jjj].split("\\[");for(var jj=0;jj<strlbls.length;jj++){if(jj%2){var strtmparray=strlbls[jj].split("\\]");switch(strtmparray[0]){case"textcolor":var nodeTmp=document.createElement("span");nodeTmp.className='LaTeXColor';if(IsColorName.test(strtmparray[1].toLowerCase())){nodeTmp.style.color=LaTeXColor[strtmparray[1].toLowerCase()];}else{nodeTmp.style.color=strtmparray[1];};nodeTmp.appendChild(document.createTextNode(strtmparray[2]));newFrag.appendChild(nodeTmp);break;case"colorbox":var nodeTmp=document.createElement("span");nodeTmp.className='LaTeXColor';if(IsColorName.test(strtmparray[1].toLowerCase())){nodeTmp.style.background=LaTeXColor[strtmparray[1].toLowerCase()];}else{nodeTmp.style.background=strtmparray[1];};nodeTmp.appendChild(document.createTextNode(strtmparray[2]));newFrag.appendChild(nodeTmp);break;case"br":newFrag.appendChild(document.createElement("br"));break;case"a":var nodeTmp=document.createElement("a");nodeTmp.className='LaTeXMathMLlabel';nodeTmp.id=strtmparray[1];nodeTmp.style.display="none";newFrag.appendChild(nodeTmp);break;default:var nodeTmp=document.createElement("span");nodeTmp.className=strtmparray[0];nodeTmp.appendChild(document.createTextNode(strtmparray[1]))
-  newFrag.appendChild(nodeTmp);}}else{newFrag.appendChild(document.createTextNode(strlbls[jj]));}}}}}}}};TheBody.parentNode.replaceChild(newFrag,TheBody);}}}
-  return TheBody;}
-  function LaTeXDivsAndRefs(thebody){var TheBody=thebody;var EndDivClass=null;var AllDivs=TheBody.getElementsByTagName("div");var lbl2id="";var lblnode=null;for(var i=AllDivs.length-1;i>=0;i--){EndDivClass=AllDivs[i].className.match(/end\w+/);if(EndDivClass!=null){EndDivClass=EndDivClass[0];var DivClass=EndDivClass.substring(3,EndDivClass.length);var EndDivNode=AllDivs[i];break;}}
-  while(EndDivClass!=null){var newFrag=document.createDocumentFragment();var RootNode=EndDivNode.parentNode;var ClassCount=1;while(EndDivNode.previousSibling!=null&&ClassCount>0){switch(EndDivNode.previousSibling.className){case EndDivClass:ClassCount++;newFrag.insertBefore(EndDivNode.previousSibling,newFrag.firstChild);break;case DivClass:if(EndDivNode.previousSibling.nodeName=="DIV"){ClassCount--;if(lbl2id!=""){EndDivNode.previousSibling.id=lbl2id;lbl2id=""}
-  if(ClassCount==0){RootNode=EndDivNode.previousSibling;}else{newFrag.insertBefore(EndDivNode.previousSibling,newFrag.firstChild);}};break;case'LaTeXMathMLlabel':lbl2id=EndDivNode.previousSibling.id;EndDivNode.parentNode.removeChild(EndDivNode.previousSibling);break;default:newFrag.insertBefore(EndDivNode.previousSibling,newFrag.firstChild);}}
-  RootNode.appendChild(newFrag);EndDivNode.parentNode.removeChild(EndDivNode);AllDivs=TheBody.getElementsByTagName("DIV");for(i=AllDivs.length-1;i>=0;i--){EndDivClass=AllDivs[i].className.match(/end\w+/);if(EndDivClass!=null){ClassCount=0;EndDivClass=EndDivClass[0];DivClass=EndDivClass.substring(3,EndDivClass.length);EndDivNode=AllDivs[i];RootNode=EndDivNode.parentNode;break;}}}
-  var AllDivs=TheBody.getElementsByTagName("div");var DIV2LI=null;for(var i=0;i<AllDivs.length;i++){if(AllDivs[i].className=="itemize"||AllDivs[i].className=="enumerate"||AllDivs[i].className=="description"){if(AllDivs[i].className=="itemize"){RootNode=document.createElement("UL");}else{RootNode=document.createElement("OL");}
-  RootNode.className='LaTeXMathML';if(AllDivs[i].hasChildNodes()){AllDivs[i].removeChild(AllDivs[i].firstChild)};while(AllDivs[i].hasChildNodes()){if(AllDivs[i].firstChild.hasChildNodes()){DIV2LI=document.createElement("LI");while(AllDivs[i].firstChild.hasChildNodes()){DIV2LI.appendChild(AllDivs[i].firstChild.firstChild);}
-  if(DIV2LI.firstChild.className=="listitemmarker"){DIV2LI.style.listStyleType="none";}
-  RootNode.appendChild(DIV2LI)}
-  AllDivs[i].removeChild(AllDivs[i].firstChild);}
-  AllDivs[i].appendChild(RootNode);}}
-  var AllAnchors=TheBody.getElementsByTagName("a");for(var i=0;i<AllAnchors.length;i++){if(AllAnchors[i].className=="ref"||AllAnchors[i].className=="cite"){var label=AllAnchors[i].href.match(/\#(\w+)/);if(label!=null){var labelNode=document.getElementById(label[1]);if(labelNode!=null){var TheSpans=labelNode.getElementsByTagName("SPAN");if(TheSpans!=null){var refNode=TheSpans[0].cloneNode(true);refNode.style.display="inline"
-  refNode.className=AllAnchors[i].className;AllAnchors[i].appendChild(refNode);}}}}}
-  return TheBody;}
-  var AMbody;var AMnoMathML=false,AMtranslated=false;function translate(spanclassAM){if(!AMtranslated){AMtranslated=true;AMinitSymbols();var LaTeXContainers=[];var AllContainers=document.getElementsByTagName('*');var ExtendName="";for(var k=0,l=0;k<AllContainers.length;k++){ExtendName=" "+AllContainers[k].className+" ";if(ExtendName.match(/\sLaTeX\s/)!=null){LaTeXContainers[l]=AllContainers[k];l++;}};if(LaTeXContainers.length>0){for(var m=0;m<LaTeXContainers.length;m++){AMbody=LaTeXContainers[m];try{AMbody=LaTeXDivsAndRefs(LaTeXpreProcess(AMbody));}catch(err){alert("Unknown Error: Defaulting to Original LaTeXMathML");}
-  if(AMbody.tagName=="PRE"){var PreChilds=document.createDocumentFragment();var DivChilds=document.createElement("DIV");while(AMbody.hasChildNodes()){DivChilds.appendChild(AMbody.firstChild);}
-  PreChilds.appendChild(DivChilds);AMbody.parentNode.replaceChild(PreChilds,AMbody);AMbody=DivChilds;}
-  AMprocessNode(AMbody,false,spanclassAM);}}else{AMbody=document.getElementsByTagName("body")[0];try{AMbody=LaTeXDivsAndRefs(LaTeXpreProcess(AMbody));}catch(err){alert("Unknown Error: Defaulting to Original LaTeXMathML");}
-  AMprocessNode(AMbody,false,spanclassAM);}}}
-  if(isIE){document.write("<object id=\"mathplayer\" classid=\"clsid:32F66A20-7614-11D4-BD11-00104BD3F987\"></object>");document.write("<?import namespace=\"m\" implementation=\"#mathplayer\"?>");}
-  function generic()
-  {translate();};if(typeof window.addEventListener!='undefined')
-  {window.addEventListener('load',generic,false);}
-  else if(typeof document.addEventListener!='undefined')
-  {document.addEventListener('load',generic,false);}
-  else if(typeof window.attachEvent!='undefined')
-  {window.attachEvent('onload',generic);}
-  else
-  {if(typeof window.onload=='function')
-  {var existing=onload;window.onload=function()
-  {existing();generic();};}
-  else
-  {window.onload=generic;}}
-  /*]]>*/
-  </script>
+  <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-AMS_CHTML-full" type="text/javascript"></script>
 </head>
 <body>
 <div class="layout">
@@ -254,7 +54,7 @@
 <div id="math" class="slide section level1">
 <h1>Math</h1>
 <ul class="incremental">
-<li><span class="LaTeX">$\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$</span></li>
+<li><span class="math inline">\(\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}\)</span></li>
 </ul>
 </div>
 </div>
diff --git a/test/tables-rstsubset.native b/test/tables-rstsubset.native
--- a/test/tables-rstsubset.native
+++ b/test/tables-rstsubset.native
@@ -53,7 +53,7 @@
   ,[Plain [Str "1"]]
   ,[Plain [Str "1"]]]]
 ,Para [Str "Multiline",Space,Str "table",Space,Str "with",Space,Str "caption:"]
-,Table [Str "Here\8217s",Space,Str "the",Space,Str "caption.",Space,Str "It",Space,Str "may",Space,Str "span",Space,Str "multiple",Space,Str "lines."] [AlignDefault,AlignDefault,AlignDefault,AlignDefault] [0.1375,0.125,0.15,0.325]
+,Table [Str "Here\8217s",Space,Str "the",Space,Str "caption.",Space,Str "It",Space,Str "may",Space,Str "span",Space,Str "multiple",Space,Str "lines."] [AlignDefault,AlignDefault,AlignDefault,AlignDefault] [0.1375,0.125,0.15,0.3375]
  [[Plain [Str "Centered",SoftBreak,Str "Header"]]
  ,[Plain [Str "Left",SoftBreak,Str "Aligned"]]
  ,[Plain [Str "Right",SoftBreak,Str "Aligned"]]
@@ -65,9 +65,9 @@
  ,[[Plain [Str "Second"]]
   ,[Plain [Str "row"]]
   ,[Plain [Str "5.0"]]
-  ,[Plain [Str "Here\8217s",Space,Str "another",Space,Str "one.",SoftBreak,Str "Note",Space,Str "the",Space,Str "blank",Space,Str "line",SoftBreak,Str "between",Space,Str "rows."]]]]
+  ,[Plain [Str "Here\8217s",Space,Str "another",Space,Str "one.",Space,Str "Note",SoftBreak,Str "the",Space,Str "blank",Space,Str "line",Space,Str "between",SoftBreak,Str "rows."]]]]
 ,Para [Str "Multiline",Space,Str "table",Space,Str "without",Space,Str "caption:"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault,AlignDefault] [0.1375,0.125,0.15,0.325]
+,Table [] [AlignDefault,AlignDefault,AlignDefault,AlignDefault] [0.1375,0.125,0.15,0.3375]
  [[Plain [Str "Centered",SoftBreak,Str "Header"]]
  ,[Plain [Str "Left",SoftBreak,Str "Aligned"]]
  ,[Plain [Str "Right",SoftBreak,Str "Aligned"]]
@@ -79,7 +79,7 @@
  ,[[Plain [Str "Second"]]
   ,[Plain [Str "row"]]
   ,[Plain [Str "5.0"]]
-  ,[Plain [Str "Here\8217s",Space,Str "another",Space,Str "one.",SoftBreak,Str "Note",Space,Str "the",Space,Str "blank",Space,Str "line",SoftBreak,Str "between",Space,Str "rows."]]]]
+  ,[Plain [Str "Here\8217s",Space,Str "another",Space,Str "one.",Space,Str "Note",SoftBreak,Str "the",Space,Str "blank",Space,Str "line",Space,Str "between",SoftBreak,Str "rows."]]]]
 ,Para [Str "Table",Space,Str "without",Space,Str "column",Space,Str "headers:"]
 ,Table [] [AlignDefault,AlignDefault,AlignDefault,AlignDefault] [7.5e-2,7.5e-2,7.5e-2,7.5e-2]
  [[]
@@ -99,7 +99,7 @@
   ,[Plain [Str "1"]]
   ,[Plain [Str "1"]]]]
 ,Para [Str "Multiline",Space,Str "table",Space,Str "without",Space,Str "column",Space,Str "headers:"]
-,Table [] [AlignDefault,AlignDefault,AlignDefault,AlignDefault] [0.1375,0.125,0.15,0.325]
+,Table [] [AlignDefault,AlignDefault,AlignDefault,AlignDefault] [0.1375,0.125,0.15,0.3375]
  [[]
  ,[]
  ,[]
@@ -111,4 +111,4 @@
  ,[[Plain [Str "Second"]]
   ,[Plain [Str "row"]]
   ,[Plain [Str "5.0"]]
-  ,[Plain [Str "Here\8217s",Space,Str "another",Space,Str "one.",SoftBreak,Str "Note",Space,Str "the",Space,Str "blank",Space,Str "line",SoftBreak,Str "between",Space,Str "rows."]]]]]
+  ,[Plain [Str "Here\8217s",Space,Str "another",Space,Str "one.",Space,Str "Note",SoftBreak,Str "the",Space,Str "blank",Space,Str "line",Space,Str "between",SoftBreak,Str "rows."]]]]]
diff --git a/test/tables.asciidoc b/test/tables.asciidoc
--- a/test/tables.asciidoc
+++ b/test/tables.asciidoc
@@ -33,7 +33,7 @@
 Multiline table with caption:
 
 .Here’s the caption. It may span multiple lines.
-[width="78%",cols="^21%,<17%,>20%,<42%",options="header",]
+[width="80%",cols="^20%,<17%,>20%,<43%",options="header",]
 |=======================================================================
 |Centered Header |Left Aligned |Right Aligned |Default aligned
 |First |row |12.0 |Example of a row that spans multiple lines.
@@ -42,7 +42,7 @@
 
 Multiline table without caption:
 
-[width="78%",cols="^21%,<17%,>20%,<42%",options="header",]
+[width="80%",cols="^20%,<17%,>20%,<43%",options="header",]
 |=======================================================================
 |Centered Header |Left Aligned |Right Aligned |Default aligned
 |First |row |12.0 |Example of a row that spans multiple lines.
@@ -60,7 +60,7 @@
 
 Multiline table without column headers:
 
-[width="78%",cols="^21%,<17%,>20%,42%",]
+[width="80%",cols="^20%,<17%,>20%,43%",]
 |=======================================================================
 |First |row |12.0 |Example of a row that spans multiple lines.
 |Second |row |5.0 |Here’s another one. Note the blank line between rows.
diff --git a/test/tables.context b/test/tables.context
--- a/test/tables.context
+++ b/test/tables.context
@@ -118,7 +118,7 @@
 \startxcell[align=middle,width={0.15\textwidth}] Centered Header \stopxcell
 \startxcell[align=right,width={0.14\textwidth}] Left Aligned \stopxcell
 \startxcell[align=left,width={0.16\textwidth}] Right Aligned \stopxcell
-\startxcell[align=right,width={0.34\textwidth}] Default aligned \stopxcell
+\startxcell[align=right,width={0.35\textwidth}] Default aligned \stopxcell
 \stopxrow
 \stopxtablehead
 \startxtablebody[body]
@@ -126,7 +126,7 @@
 \startxcell[align=middle,width={0.15\textwidth}] First \stopxcell
 \startxcell[align=right,width={0.14\textwidth}] row \stopxcell
 \startxcell[align=left,width={0.16\textwidth}] 12.0 \stopxcell
-\startxcell[align=right,width={0.34\textwidth}] Example of a row that spans
+\startxcell[align=right,width={0.35\textwidth}] Example of a row that spans
 multiple lines. \stopxcell
 \stopxrow
 \stopxtablebody
@@ -135,7 +135,7 @@
 \startxcell[align=middle,width={0.15\textwidth}] Second \stopxcell
 \startxcell[align=right,width={0.14\textwidth}] row \stopxcell
 \startxcell[align=left,width={0.16\textwidth}] 5.0 \stopxcell
-\startxcell[align=right,width={0.34\textwidth}] Here's another one. Note the
+\startxcell[align=right,width={0.35\textwidth}] Here's another one. Note the
 blank line between rows. \stopxcell
 \stopxrow
 \stopxtablefoot
@@ -151,7 +151,7 @@
 \startxcell[align=middle,width={0.15\textwidth}] Centered Header \stopxcell
 \startxcell[align=right,width={0.14\textwidth}] Left Aligned \stopxcell
 \startxcell[align=left,width={0.16\textwidth}] Right Aligned \stopxcell
-\startxcell[align=right,width={0.34\textwidth}] Default aligned \stopxcell
+\startxcell[align=right,width={0.35\textwidth}] Default aligned \stopxcell
 \stopxrow
 \stopxtablehead
 \startxtablebody[body]
@@ -159,7 +159,7 @@
 \startxcell[align=middle,width={0.15\textwidth}] First \stopxcell
 \startxcell[align=right,width={0.14\textwidth}] row \stopxcell
 \startxcell[align=left,width={0.16\textwidth}] 12.0 \stopxcell
-\startxcell[align=right,width={0.34\textwidth}] Example of a row that spans
+\startxcell[align=right,width={0.35\textwidth}] Example of a row that spans
 multiple lines. \stopxcell
 \stopxrow
 \stopxtablebody
@@ -168,7 +168,7 @@
 \startxcell[align=middle,width={0.15\textwidth}] Second \stopxcell
 \startxcell[align=right,width={0.14\textwidth}] row \stopxcell
 \startxcell[align=left,width={0.16\textwidth}] 5.0 \stopxcell
-\startxcell[align=right,width={0.34\textwidth}] Here's another one. Note the
+\startxcell[align=right,width={0.35\textwidth}] Here's another one. Note the
 blank line between rows. \stopxcell
 \stopxrow
 \stopxtablefoot
@@ -213,7 +213,7 @@
 \startxcell[align=middle,width={0.15\textwidth}] First \stopxcell
 \startxcell[align=right,width={0.14\textwidth}] row \stopxcell
 \startxcell[align=left,width={0.16\textwidth}] 12.0 \stopxcell
-\startxcell[width={0.34\textwidth}] Example of a row that spans multiple
+\startxcell[width={0.35\textwidth}] Example of a row that spans multiple
 lines. \stopxcell
 \stopxrow
 \stopxtablebody
@@ -222,7 +222,7 @@
 \startxcell[align=middle,width={0.15\textwidth}] Second \stopxcell
 \startxcell[align=right,width={0.14\textwidth}] row \stopxcell
 \startxcell[align=left,width={0.16\textwidth}] 5.0 \stopxcell
-\startxcell[width={0.34\textwidth}] Here's another one. Note the blank line
+\startxcell[width={0.35\textwidth}] Here's another one. Note the blank line
 between rows. \stopxcell
 \stopxrow
 \stopxtablefoot
diff --git a/test/tables.custom b/test/tables.custom
--- a/test/tables.custom
+++ b/test/tables.custom
@@ -95,7 +95,7 @@
 <col width="15%" />
 <col width="14%" />
 <col width="16%" />
-<col width="34%" />
+<col width="35%" />
 <tr class="header">
 <th align="center">Centered
 Header</th>
@@ -127,7 +127,7 @@
 <col width="15%" />
 <col width="14%" />
 <col width="16%" />
-<col width="34%" />
+<col width="35%" />
 <tr class="header">
 <th align="center">Centered
 Header</th>
@@ -182,7 +182,7 @@
 <col width="15%" />
 <col width="14%" />
 <col width="16%" />
-<col width="34%" />
+<col width="35%" />
 <tr class="odd">
 <td align="center">First</td>
 <td align="left">row</td>
diff --git a/test/tables.docbook4 b/test/tables.docbook4
--- a/test/tables.docbook4
+++ b/test/tables.docbook4
@@ -228,7 +228,7 @@
     <colspec colwidth="15*" align="center" />
     <colspec colwidth="13*" align="left" />
     <colspec colwidth="16*" align="right" />
-    <colspec colwidth="33*" align="left" />
+    <colspec colwidth="35*" align="left" />
     <thead>
       <row>
         <entry>
@@ -285,7 +285,7 @@
     <colspec colwidth="15*" align="center" />
     <colspec colwidth="13*" align="left" />
     <colspec colwidth="16*" align="right" />
-    <colspec colwidth="33*" align="left" />
+    <colspec colwidth="35*" align="left" />
     <thead>
       <row>
         <entry>
@@ -397,7 +397,7 @@
     <colspec colwidth="15*" align="center" />
     <colspec colwidth="13*" align="left" />
     <colspec colwidth="16*" align="right" />
-    <colspec colwidth="33*" align="left" />
+    <colspec colwidth="35*" align="left" />
     <tbody>
       <row>
         <entry>
diff --git a/test/tables.docbook5 b/test/tables.docbook5
--- a/test/tables.docbook5
+++ b/test/tables.docbook5
@@ -228,7 +228,7 @@
     <colspec colwidth="15*" align="center" />
     <colspec colwidth="13*" align="left" />
     <colspec colwidth="16*" align="right" />
-    <colspec colwidth="33*" align="left" />
+    <colspec colwidth="35*" align="left" />
     <thead>
       <row>
         <entry>
@@ -285,7 +285,7 @@
     <colspec colwidth="15*" align="center" />
     <colspec colwidth="13*" align="left" />
     <colspec colwidth="16*" align="right" />
-    <colspec colwidth="33*" align="left" />
+    <colspec colwidth="35*" align="left" />
     <thead>
       <row>
         <entry>
@@ -397,7 +397,7 @@
     <colspec colwidth="15*" align="center" />
     <colspec colwidth="13*" align="left" />
     <colspec colwidth="16*" align="right" />
-    <colspec colwidth="33*" align="left" />
+    <colspec colwidth="35*" align="left" />
     <tbody>
       <row>
         <entry>
diff --git a/test/tables.fb2 b/test/tables.fb2
--- a/test/tables.fb2
+++ b/test/tables.fb2
@@ -1,3 +1,16 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink"><description><title-info><genre>unrecognised</genre></title-info><document-info><program-used>pandoc</program-used></document-info></description><body><title><p /></title><section><p>Simple table with caption:</p><table><tr><th align="right">Right</th><th align="left">Left</th><th align="center">Center</th><th align="left">Default</th></tr><tr><td align="right">12</td><td align="left">12</td><td align="center">12</td><td align="left">12</td></tr><tr><td align="right">123</td><td align="left">123</td><td align="center">123</td><td align="left">123</td></tr><tr><td align="right">1</td><td align="left">1</td><td align="center">1</td><td align="left">1</td></tr></table><p><emphasis>Demonstration of simple table syntax.</emphasis></p><p>Simple table without caption:</p><table><tr><th align="right">Right</th><th align="left">Left</th><th align="center">Center</th><th align="left">Default</th></tr><tr><td align="right">12</td><td align="left">12</td><td align="center">12</td><td align="left">12</td></tr><tr><td align="right">123</td><td align="left">123</td><td align="center">123</td><td align="left">123</td></tr><tr><td align="right">1</td><td align="left">1</td><td align="center">1</td><td align="left">1</td></tr></table><p><emphasis /></p><p>Simple table indented two spaces:</p><table><tr><th align="right">Right</th><th align="left">Left</th><th align="center">Center</th><th align="left">Default</th></tr><tr><td align="right">12</td><td align="left">12</td><td align="center">12</td><td align="left">12</td></tr><tr><td align="right">123</td><td align="left">123</td><td align="center">123</td><td align="left">123</td></tr><tr><td align="right">1</td><td align="left">1</td><td align="center">1</td><td align="left">1</td></tr></table><p><emphasis>Demonstration of simple table syntax.</emphasis></p><p>Multiline table with caption:</p><table><tr><th align="center">Centered Header</th><th align="left">Left Aligned</th><th align="right">Right Aligned</th><th align="left">Default aligned</th></tr><tr><td align="center">First</td><td align="left">row</td><td align="right">12.0</td><td align="left">Example of a row that spans multiple lines.</td></tr><tr><td align="center">Second</td><td align="left">row</td><td align="right">5.0</td><td align="left">Here’s another one. Note the blank line between rows.</td></tr></table><p><emphasis>Here’s the caption. It may span multiple lines.</emphasis></p><p>Multiline table without caption:</p><table><tr><th align="center">Centered Header</th><th align="left">Left Aligned</th><th align="right">Right Aligned</th><th align="left">Default aligned</th></tr><tr><td align="center">First</td><td align="left">row</td><td align="right">12.0</td><td align="left">Example of a row that spans multiple lines.</td></tr><tr><td align="center">Second</td><td align="left">row</td><td align="right">5.0</td><td align="left">Here’s another one. Note the blank line between rows.</td></tr></table><p><emphasis /></p><p>Table without column headers:</p><table><tr><th align="right" /><th align="left" /><th align="center" /><th align="right" /></tr><tr><td align="right">12</td><td align="left">12</td><td align="center">12</td><td align="right">12</td></tr><tr><td align="right">123</td><td align="left">123</td><td align="center">123</td><td align="right">123</td></tr><tr><td align="right">1</td><td align="left">1</td><td align="center">1</td><td align="right">1</td></tr></table><p><emphasis /></p><p>Multiline table without column headers:</p><table><tr><th align="center" /><th align="left" /><th align="right" /><th align="left" /></tr><tr><td align="center">First</td><td align="left">row</td><td align="right">12.0</td><td align="left">Example of a row that spans multiple lines.</td></tr><tr><td align="center">Second</td><td align="left">row</td><td align="right">5.0</td><td align="left">Here’s another one. Note the blank line between rows.</td></tr></table><p><emphasis /></p></section></body></FictionBook>
+<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink"><description><title-info><genre>unrecognised</genre></title-info><document-info><program-used>pandoc</program-used></document-info></description><body><title><p /></title><section><p>Simple table with caption:</p><table><tr><th align="right">Right</th><th align="left">Left</th><th align="center">Center</th><th align="left">Default</th></tr><tr><td align="right">12</td><td align="left">12</td><td align="center">12</td><td align="left">12</td></tr><tr><td align="right">123</td><td align="left">123</td><td align="center">123</td><td align="left">123</td></tr><tr><td align="right">1</td><td align="left">1</td><td align="center">1</td><td align="left">1</td></tr></table><p><emphasis>Demonstration of simple table syntax.</emphasis></p><p>Simple table without caption:</p><table><tr><th align="right">Right</th><th align="left">Left</th><th align="center">Center</th><th align="left">Default</th></tr><tr><td align="right">12</td><td align="left">12</td><td align="center">12</td><td align="left">12</td></tr><tr><td align="right">123</td><td align="left">123</td><td align="center">123</td><td align="left">123</td></tr><tr><td align="right">1</td><td align="left">1</td><td align="center">1</td><td align="left">1</td></tr></table><p><emphasis /></p><p>Simple table indented two spaces:</p><table><tr><th align="right">Right</th><th align="left">Left</th><th align="center">Center</th><th align="left">Default</th></tr><tr><td align="right">12</td><td align="left">12</td><td align="center">12</td><td align="left">12</td></tr><tr><td align="right">123</td><td align="left">123</td><td align="center">123</td><td align="left">123</td></tr><tr><td align="right">1</td><td align="left">1</td><td align="center">1</td><td align="left">1</td></tr></table><p><emphasis>Demonstration of simple table syntax.</emphasis></p><p>Multiline table with caption:</p><table><tr><th align="center">Centered
+Header</th><th align="left">Left
+Aligned</th><th align="right">Right
+Aligned</th><th align="left">Default aligned</th></tr><tr><td align="center">First</td><td align="left">row</td><td align="right">12.0</td><td align="left">Example of a row that spans
+multiple lines.</td></tr><tr><td align="center">Second</td><td align="left">row</td><td align="right">5.0</td><td align="left">Here’s another one. Note
+the blank line between rows.</td></tr></table><p><emphasis>Here’s the caption.
+It may span multiple lines.</emphasis></p><p>Multiline table without caption:</p><table><tr><th align="center">Centered
+Header</th><th align="left">Left
+Aligned</th><th align="right">Right
+Aligned</th><th align="left">Default aligned</th></tr><tr><td align="center">First</td><td align="left">row</td><td align="right">12.0</td><td align="left">Example of a row that spans
+multiple lines.</td></tr><tr><td align="center">Second</td><td align="left">row</td><td align="right">5.0</td><td align="left">Here’s another one. Note
+the blank line between rows.</td></tr></table><p><emphasis /></p><p>Table without column headers:</p><table><tr><th align="right" /><th align="left" /><th align="center" /><th align="right" /></tr><tr><td align="right">12</td><td align="left">12</td><td align="center">12</td><td align="right">12</td></tr><tr><td align="right">123</td><td align="left">123</td><td align="center">123</td><td align="right">123</td></tr><tr><td align="right">1</td><td align="left">1</td><td align="center">1</td><td align="right">1</td></tr></table><p><emphasis /></p><p>Multiline table without column headers:</p><table><tr><th align="center" /><th align="left" /><th align="right" /><th align="left" /></tr><tr><td align="center">First</td><td align="left">row</td><td align="right">12.0</td><td align="left">Example of a row that spans
+multiple lines.</td></tr><tr><td align="center">Second</td><td align="left">row</td><td align="right">5.0</td><td align="left">Here’s another one. Note
+the blank line between rows.</td></tr></table><p><emphasis /></p></section></body></FictionBook>
 
diff --git a/test/tables.haddock b/test/tables.haddock
--- a/test/tables.haddock
+++ b/test/tables.haddock
@@ -40,33 +40,33 @@
 
 Multiline table with caption:
 
-> +----------+---------+-----------+-------------------------+
-> | Centered | Left    | Right     | Default aligned         |
-> | Header   | Aligned | Aligned   |                         |
-> +==========+=========+===========+=========================+
-> | First    | row     | 12.0      | Example of a row that   |
-> |          |         |           | spans multiple lines.   |
-> +----------+---------+-----------+-------------------------+
-> | Second   | row     | 5.0       | Here’s another one.     |
-> |          |         |           | Note the blank line     |
-> |          |         |           | between rows.           |
-> +----------+---------+-----------+-------------------------+
+> +----------+---------+-----------+--------------------------+
+> | Centered | Left    | Right     | Default aligned          |
+> | Header   | Aligned | Aligned   |                          |
+> +==========+=========+===========+==========================+
+> | First    | row     | 12.0      | Example of a row that    |
+> |          |         |           | spans multiple lines.    |
+> +----------+---------+-----------+--------------------------+
+> | Second   | row     | 5.0       | Here’s another one. Note |
+> |          |         |           | the blank line between   |
+> |          |         |           | rows.                    |
+> +----------+---------+-----------+--------------------------+
 >
 > Here’s the caption. It may span multiple lines.
 
 Multiline table without caption:
 
-> +----------+---------+-----------+-------------------------+
-> | Centered | Left    | Right     | Default aligned         |
-> | Header   | Aligned | Aligned   |                         |
-> +==========+=========+===========+=========================+
-> | First    | row     | 12.0      | Example of a row that   |
-> |          |         |           | spans multiple lines.   |
-> +----------+---------+-----------+-------------------------+
-> | Second   | row     | 5.0       | Here’s another one.     |
-> |          |         |           | Note the blank line     |
-> |          |         |           | between rows.           |
-> +----------+---------+-----------+-------------------------+
+> +----------+---------+-----------+--------------------------+
+> | Centered | Left    | Right     | Default aligned          |
+> | Header   | Aligned | Aligned   |                          |
+> +==========+=========+===========+==========================+
+> | First    | row     | 12.0      | Example of a row that    |
+> |          |         |           | spans multiple lines.    |
+> +----------+---------+-----------+--------------------------+
+> | Second   | row     | 5.0       | Here’s another one. Note |
+> |          |         |           | the blank line between   |
+> |          |         |           | rows.                    |
+> +----------+---------+-----------+--------------------------+
 
 Table without column headers:
 
@@ -80,11 +80,11 @@
 
 Multiline table without column headers:
 
-> +----------+---------+-----------+-------------------------+
-> | First    | row     | 12.0      | Example of a row that   |
-> |          |         |           | spans multiple lines.   |
-> +----------+---------+-----------+-------------------------+
-> | Second   | row     | 5.0       | Here’s another one.     |
-> |          |         |           | Note the blank line     |
-> |          |         |           | between rows.           |
-> +----------+---------+-----------+-------------------------+
+> +----------+---------+-----------+--------------------------+
+> | First    | row     | 12.0      | Example of a row that    |
+> |          |         |           | spans multiple lines.    |
+> +----------+---------+-----------+--------------------------+
+> | Second   | row     | 5.0       | Here’s another one. Note |
+> |          |         |           | the blank line between   |
+> |          |         |           | rows.                    |
+> +----------+---------+-----------+--------------------------+
diff --git a/test/tables.html4 b/test/tables.html4
--- a/test/tables.html4
+++ b/test/tables.html4
@@ -94,13 +94,13 @@
 </tbody>
 </table>
 <p>Multiline table with caption:</p>
-<table style="width:79%;">
+<table style="width:80%;">
 <caption>Here’s the caption. It may span multiple lines.</caption>
 <colgroup>
 <col width="15%" />
 <col width="13%" />
 <col width="16%" />
-<col width="33%" />
+<col width="35%" />
 </colgroup>
 <thead>
 <tr class="header">
@@ -126,12 +126,12 @@
 </tbody>
 </table>
 <p>Multiline table without caption:</p>
-<table style="width:79%;">
+<table style="width:80%;">
 <colgroup>
 <col width="15%" />
 <col width="13%" />
 <col width="16%" />
-<col width="33%" />
+<col width="35%" />
 </colgroup>
 <thead>
 <tr class="header">
@@ -180,12 +180,12 @@
 </tbody>
 </table>
 <p>Multiline table without column headers:</p>
-<table style="width:79%;">
+<table style="width:80%;">
 <colgroup>
 <col width="15%" />
 <col width="13%" />
 <col width="16%" />
-<col width="33%" />
+<col width="35%" />
 </colgroup>
 <tbody>
 <tr class="odd">
diff --git a/test/tables.html5 b/test/tables.html5
--- a/test/tables.html5
+++ b/test/tables.html5
@@ -94,13 +94,13 @@
 </tbody>
 </table>
 <p>Multiline table with caption:</p>
-<table style="width:79%;">
+<table style="width:80%;">
 <caption>Here’s the caption. It may span multiple lines.</caption>
 <colgroup>
 <col style="width: 15%" />
 <col style="width: 13%" />
 <col style="width: 16%" />
-<col style="width: 33%" />
+<col style="width: 35%" />
 </colgroup>
 <thead>
 <tr class="header">
@@ -126,12 +126,12 @@
 </tbody>
 </table>
 <p>Multiline table without caption:</p>
-<table style="width:79%;">
+<table style="width:80%;">
 <colgroup>
 <col style="width: 15%" />
 <col style="width: 13%" />
 <col style="width: 16%" />
-<col style="width: 33%" />
+<col style="width: 35%" />
 </colgroup>
 <thead>
 <tr class="header">
@@ -180,12 +180,12 @@
 </tbody>
 </table>
 <p>Multiline table without column headers:</p>
-<table style="width:79%;">
+<table style="width:80%;">
 <colgroup>
 <col style="width: 15%" />
 <col style="width: 13%" />
 <col style="width: 16%" />
-<col style="width: 33%" />
+<col style="width: 35%" />
 </colgroup>
 <tbody>
 <tr class="odd">
diff --git a/test/tables.icml b/test/tables.icml
--- a/test/tables.icml
+++ b/test/tables.icml
@@ -395,7 +395,7 @@
   <Column Name="0" SingleColumnWidth="75.0" />
   <Column Name="1" SingleColumnWidth="68.75" />
   <Column Name="2" SingleColumnWidth="81.25" />
-  <Column Name="3" SingleColumnWidth="168.75" />
+  <Column Name="3" SingleColumnWidth="175.0" />
   <Cell Name="0:0" AppliedCellStyle="CellStyle/Cell">
     <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/TablePar &gt; TableHeader &gt; CenterAlign">
       <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
@@ -497,7 +497,7 @@
   <Column Name="0" SingleColumnWidth="75.0" />
   <Column Name="1" SingleColumnWidth="68.75" />
   <Column Name="2" SingleColumnWidth="81.25" />
-  <Column Name="3" SingleColumnWidth="168.75" />
+  <Column Name="3" SingleColumnWidth="175.0" />
   <Cell Name="0:0" AppliedCellStyle="CellStyle/Cell">
     <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/TablePar &gt; TableHeader &gt; CenterAlign">
       <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
@@ -695,7 +695,7 @@
   <Column Name="0" SingleColumnWidth="75.0" />
   <Column Name="1" SingleColumnWidth="68.75" />
   <Column Name="2" SingleColumnWidth="81.25" />
-  <Column Name="3" SingleColumnWidth="168.75" />
+  <Column Name="3" SingleColumnWidth="175.0" />
   <Cell Name="0:0" AppliedCellStyle="CellStyle/Cell">
     <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/TablePar &gt; CenterAlign">
       <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
diff --git a/test/tables.jats b/test/tables.jats
--- a/test/tables.jats
+++ b/test/tables.jats
@@ -122,7 +122,7 @@
     <col width="15*" align="center" />
     <col width="13*" align="left" />
     <col width="16*" align="right" />
-    <col width="33*" align="left" />
+    <col width="35*" align="left" />
     <thead>
       <tr>
         <th>Centered Header</th>
@@ -152,7 +152,7 @@
   <col width="15*" align="center" />
   <col width="13*" align="left" />
   <col width="16*" align="right" />
-  <col width="33*" align="left" />
+  <col width="35*" align="left" />
   <thead>
     <tr>
       <th>Centered Header</th>
@@ -208,7 +208,7 @@
   <col width="15*" align="center" />
   <col width="13*" align="left" />
   <col width="16*" align="right" />
-  <col width="33*" align="left" />
+  <col width="35*" align="left" />
   <tbody>
     <tr>
       <td>First</td>
diff --git a/test/tables.latex b/test/tables.latex
--- a/test/tables.latex
+++ b/test/tables.latex
@@ -58,7 +58,7 @@
 Left Aligned\strut
 \end{minipage} & \begin{minipage}[b]{0.14\columnwidth}\raggedleft
 Right Aligned\strut
-\end{minipage} & \begin{minipage}[b]{0.30\columnwidth}\raggedright
+\end{minipage} & \begin{minipage}[b]{0.31\columnwidth}\raggedright
 Default aligned\strut
 \end{minipage}\tabularnewline
 \midrule
@@ -70,7 +70,7 @@
 Left Aligned\strut
 \end{minipage} & \begin{minipage}[b]{0.14\columnwidth}\raggedleft
 Right Aligned\strut
-\end{minipage} & \begin{minipage}[b]{0.30\columnwidth}\raggedright
+\end{minipage} & \begin{minipage}[b]{0.31\columnwidth}\raggedright
 Default aligned\strut
 \end{minipage}\tabularnewline
 \midrule
@@ -81,7 +81,7 @@
 row\strut
 \end{minipage} & \begin{minipage}[t]{0.14\columnwidth}\raggedleft
 12.0\strut
-\end{minipage} & \begin{minipage}[t]{0.30\columnwidth}\raggedright
+\end{minipage} & \begin{minipage}[t]{0.31\columnwidth}\raggedright
 Example of a row that spans multiple lines.\strut
 \end{minipage}\tabularnewline
 \begin{minipage}[t]{0.13\columnwidth}\centering
@@ -90,7 +90,7 @@
 row\strut
 \end{minipage} & \begin{minipage}[t]{0.14\columnwidth}\raggedleft
 5.0\strut
-\end{minipage} & \begin{minipage}[t]{0.30\columnwidth}\raggedright
+\end{minipage} & \begin{minipage}[t]{0.31\columnwidth}\raggedright
 Here's another one. Note the blank line between rows.\strut
 \end{minipage}\tabularnewline
 \bottomrule
@@ -106,7 +106,7 @@
 Left Aligned\strut
 \end{minipage} & \begin{minipage}[b]{0.14\columnwidth}\raggedleft
 Right Aligned\strut
-\end{minipage} & \begin{minipage}[b]{0.30\columnwidth}\raggedright
+\end{minipage} & \begin{minipage}[b]{0.31\columnwidth}\raggedright
 Default aligned\strut
 \end{minipage}\tabularnewline
 \midrule
@@ -117,7 +117,7 @@
 row\strut
 \end{minipage} & \begin{minipage}[t]{0.14\columnwidth}\raggedleft
 12.0\strut
-\end{minipage} & \begin{minipage}[t]{0.30\columnwidth}\raggedright
+\end{minipage} & \begin{minipage}[t]{0.31\columnwidth}\raggedright
 Example of a row that spans multiple lines.\strut
 \end{minipage}\tabularnewline
 \begin{minipage}[t]{0.13\columnwidth}\centering
@@ -126,7 +126,7 @@
 row\strut
 \end{minipage} & \begin{minipage}[t]{0.14\columnwidth}\raggedleft
 5.0\strut
-\end{minipage} & \begin{minipage}[t]{0.30\columnwidth}\raggedright
+\end{minipage} & \begin{minipage}[t]{0.31\columnwidth}\raggedright
 Here's another one. Note the blank line between rows.\strut
 \end{minipage}\tabularnewline
 \bottomrule
@@ -154,7 +154,7 @@
 row\strut
 \end{minipage} & \begin{minipage}[t]{0.14\columnwidth}\raggedleft
 12.0\strut
-\end{minipage} & \begin{minipage}[t]{0.30\columnwidth}\raggedright
+\end{minipage} & \begin{minipage}[t]{0.31\columnwidth}\raggedright
 Example of a row that spans multiple lines.\strut
 \end{minipage}\tabularnewline
 \begin{minipage}[t]{0.13\columnwidth}\centering
@@ -163,7 +163,7 @@
 row\strut
 \end{minipage} & \begin{minipage}[t]{0.14\columnwidth}\raggedleft
 5.0\strut
-\end{minipage} & \begin{minipage}[t]{0.30\columnwidth}\raggedright
+\end{minipage} & \begin{minipage}[t]{0.31\columnwidth}\raggedright
 Here's another one. Note the blank line between rows.\strut
 \end{minipage}\tabularnewline
 \bottomrule
diff --git a/test/tables.man b/test/tables.man
--- a/test/tables.man
+++ b/test/tables.man
@@ -138,7 +138,7 @@
 Here's the caption. It may span multiple lines.
 .TS
 tab(@);
-cw(10.5n) lw(9.6n) rw(11.4n) lw(23.6n).
+cw(10.5n) lw(9.6n) rw(11.4n) lw(24.5n).
 T{
 Centered Header
 T}@T{
@@ -174,7 +174,7 @@
 .PP
 .TS
 tab(@);
-cw(10.5n) lw(9.6n) rw(11.4n) lw(23.6n).
+cw(10.5n) lw(9.6n) rw(11.4n) lw(24.5n).
 T{
 Centered Header
 T}@T{
@@ -244,7 +244,7 @@
 .PP
 .TS
 tab(@);
-cw(10.5n) lw(9.6n) rw(11.4n) lw(23.6n).
+cw(10.5n) lw(9.6n) rw(11.4n) lw(24.5n).
 T{
 First
 T}@T{
diff --git a/test/tables.markdown b/test/tables.markdown
--- a/test/tables.markdown
+++ b/test/tables.markdown
@@ -28,33 +28,33 @@
 
 Multiline table with caption:
 
-  -------------------------------------------------------------
+  --------------------------------------------------------------
    Centered   Left              Right Default aligned
     Header    Aligned         Aligned 
-  ----------- ---------- ------------ -------------------------
+  ----------- ---------- ------------ --------------------------
      First    row                12.0 Example of a row that
                                       spans multiple lines.
 
     Second    row                 5.0 Here's another one. Note
                                       the blank line between
                                       rows.
-  -------------------------------------------------------------
+  --------------------------------------------------------------
 
   : Here's the caption. It may span multiple lines.
 
 Multiline table without caption:
 
-  -------------------------------------------------------------
+  --------------------------------------------------------------
    Centered   Left              Right Default aligned
     Header    Aligned         Aligned 
-  ----------- ---------- ------------ -------------------------
+  ----------- ---------- ------------ --------------------------
      First    row                12.0 Example of a row that
                                       spans multiple lines.
 
     Second    row                 5.0 Here's another one. Note
                                       the blank line between
                                       rows.
-  -------------------------------------------------------------
+  --------------------------------------------------------------
 
 Table without column headers:
 
@@ -66,11 +66,11 @@
 
 Multiline table without column headers:
 
-  ----------- ---------- ------------ -------------------------
+  ----------- ---------- ------------ --------------------------
      First    row                12.0 Example of a row that
                                       spans multiple lines.
 
     Second    row                 5.0 Here's another one. Note
                                       the blank line between
                                       rows.
-  ----------- ---------- ------------ -------------------------
+  ----------- ---------- ------------ --------------------------
diff --git a/test/tables.mediawiki b/test/tables.mediawiki
--- a/test/tables.mediawiki
+++ b/test/tables.mediawiki
@@ -79,7 +79,7 @@
 !align="center" width="15%"| Centered Header
 !width="13%"| Left Aligned
 !align="right" width="16%"| Right Aligned
-!width="33%"| Default aligned
+!width="35%"| Default aligned
 |-
 |align="center"| First
 | row
@@ -98,7 +98,7 @@
 !align="center" width="15%"| Centered Header
 !width="13%"| Left Aligned
 !align="right" width="16%"| Right Aligned
-!width="33%"| Default aligned
+!width="35%"| Default aligned
 |-
 |align="center"| First
 | row
@@ -136,7 +136,7 @@
 |align="center" width="15%"| First
 |width="13%"| row
 |align="right" width="16%"| 12.0
-|width="33%"| Example of a row that spans multiple lines.
+|width="35%"| Example of a row that spans multiple lines.
 |-
 |align="center"| Second
 | row
diff --git a/test/tables.ms b/test/tables.ms
--- a/test/tables.ms
+++ b/test/tables.ms
@@ -135,10 +135,10 @@
 .LP
 Multiline table with caption:
 .PP
-Here's the caption. It may span multiple lines.
+Here’s the caption. It may span multiple lines.
 .TS
 delim(@@) tab(	);
-cw(10.5n) lw(9.6n) rw(11.4n) lw(23.6n).
+cw(10.5n) lw(9.6n) rw(11.4n) lw(24.5n).
 T{
 Centered Header
 T}	T{
@@ -165,7 +165,7 @@
 T}	T{
 5.0
 T}	T{
-Here's another one.
+Here’s another one.
 Note the blank line between rows.
 T}
 .TE
@@ -174,7 +174,7 @@
 .PP
 .TS
 delim(@@) tab(	);
-cw(10.5n) lw(9.6n) rw(11.4n) lw(23.6n).
+cw(10.5n) lw(9.6n) rw(11.4n) lw(24.5n).
 T{
 Centered Header
 T}	T{
@@ -201,7 +201,7 @@
 T}	T{
 5.0
 T}	T{
-Here's another one.
+Here’s another one.
 Note the blank line between rows.
 T}
 .TE
@@ -244,7 +244,7 @@
 .PP
 .TS
 delim(@@) tab(	);
-cw(10.5n) lw(9.6n) rw(11.4n) lw(23.6n).
+cw(10.5n) lw(9.6n) rw(11.4n) lw(24.5n).
 T{
 First
 T}	T{
@@ -261,7 +261,7 @@
 T}	T{
 5.0
 T}	T{
-Here's another one.
+Here’s another one.
 Note the blank line between rows.
 T}
 .TE
diff --git a/test/tables.native b/test/tables.native
--- a/test/tables.native
+++ b/test/tables.native
@@ -53,7 +53,7 @@
   ,[Plain [Str "1"]]
   ,[Plain [Str "1"]]]]
 ,Para [Str "Multiline",Space,Str "table",Space,Str "with",Space,Str "caption:"]
-,Table [Str "Here\8217s",Space,Str "the",Space,Str "caption.",SoftBreak,Str "It",Space,Str "may",Space,Str "span",Space,Str "multiple",Space,Str "lines."] [AlignCenter,AlignLeft,AlignRight,AlignLeft] [0.15,0.1375,0.1625,0.3375]
+,Table [Str "Here\8217s",Space,Str "the",Space,Str "caption.",SoftBreak,Str "It",Space,Str "may",Space,Str "span",Space,Str "multiple",Space,Str "lines."] [AlignCenter,AlignLeft,AlignRight,AlignLeft] [0.15,0.1375,0.1625,0.35]
  [[Plain [Str "Centered",SoftBreak,Str "Header"]]
  ,[Plain [Str "Left",SoftBreak,Str "Aligned"]]
  ,[Plain [Str "Right",SoftBreak,Str "Aligned"]]
@@ -67,7 +67,7 @@
   ,[Plain [Str "5.0"]]
   ,[Plain [Str "Here\8217s",Space,Str "another",Space,Str "one.",Space,Str "Note",SoftBreak,Str "the",Space,Str "blank",Space,Str "line",Space,Str "between",Space,Str "rows."]]]]
 ,Para [Str "Multiline",Space,Str "table",Space,Str "without",Space,Str "caption:"]
-,Table [] [AlignCenter,AlignLeft,AlignRight,AlignLeft] [0.15,0.1375,0.1625,0.3375]
+,Table [] [AlignCenter,AlignLeft,AlignRight,AlignLeft] [0.15,0.1375,0.1625,0.35]
  [[Plain [Str "Centered",SoftBreak,Str "Header"]]
  ,[Plain [Str "Left",SoftBreak,Str "Aligned"]]
  ,[Plain [Str "Right",SoftBreak,Str "Aligned"]]
@@ -99,7 +99,7 @@
   ,[Plain [Str "1"]]
   ,[Plain [Str "1"]]]]
 ,Para [Str "Multiline",Space,Str "table",Space,Str "without",Space,Str "column",Space,Str "headers:"]
-,Table [] [AlignCenter,AlignLeft,AlignRight,AlignDefault] [0.15,0.1375,0.1625,0.3375]
+,Table [] [AlignCenter,AlignLeft,AlignRight,AlignDefault] [0.15,0.1375,0.1625,0.35]
  [[]
  ,[]
  ,[]
diff --git a/test/tables.plain b/test/tables.plain
--- a/test/tables.plain
+++ b/test/tables.plain
@@ -28,33 +28,33 @@
 
 Multiline table with caption:
 
-  -------------------------------------------------------------
+  --------------------------------------------------------------
    Centered   Left              Right Default aligned
     Header    Aligned         Aligned 
-  ----------- ---------- ------------ -------------------------
+  ----------- ---------- ------------ --------------------------
      First    row                12.0 Example of a row that
                                       spans multiple lines.
 
     Second    row                 5.0 Here’s another one. Note
                                       the blank line between
                                       rows.
-  -------------------------------------------------------------
+  --------------------------------------------------------------
 
   : Here’s the caption. It may span multiple lines.
 
 Multiline table without caption:
 
-  -------------------------------------------------------------
+  --------------------------------------------------------------
    Centered   Left              Right Default aligned
     Header    Aligned         Aligned 
-  ----------- ---------- ------------ -------------------------
+  ----------- ---------- ------------ --------------------------
      First    row                12.0 Example of a row that
                                       spans multiple lines.
 
     Second    row                 5.0 Here’s another one. Note
                                       the blank line between
                                       rows.
-  -------------------------------------------------------------
+  --------------------------------------------------------------
 
 Table without column headers:
 
@@ -66,11 +66,11 @@
 
 Multiline table without column headers:
 
-  ----------- ---------- ------------ -------------------------
+  ----------- ---------- ------------ --------------------------
      First    row                12.0 Example of a row that
                                       spans multiple lines.
 
     Second    row                 5.0 Here’s another one. Note
                                       the blank line between
                                       rows.
-  ----------- ---------- ------------ -------------------------
+  ----------- ---------- ------------ --------------------------
diff --git a/test/tables.rst b/test/tables.rst
--- a/test/tables.rst
+++ b/test/tables.rst
@@ -42,31 +42,31 @@
 
 .. table:: Here’s the caption. It may span multiple lines.
 
-   +----------+---------+-----------+-------------------------+
-   | Centered | Left    | Right     | Default aligned         |
-   | Header   | Aligned | Aligned   |                         |
-   +==========+=========+===========+=========================+
-   | First    | row     | 12.0      | Example of a row that   |
-   |          |         |           | spans multiple lines.   |
-   +----------+---------+-----------+-------------------------+
-   | Second   | row     | 5.0       | Here’s another one.     |
-   |          |         |           | Note the blank line     |
-   |          |         |           | between rows.           |
-   +----------+---------+-----------+-------------------------+
+   +----------+---------+-----------+--------------------------+
+   | Centered | Left    | Right     | Default aligned          |
+   | Header   | Aligned | Aligned   |                          |
+   +==========+=========+===========+==========================+
+   | First    | row     | 12.0      | Example of a row that    |
+   |          |         |           | spans multiple lines.    |
+   +----------+---------+-----------+--------------------------+
+   | Second   | row     | 5.0       | Here’s another one. Note |
+   |          |         |           | the blank line between   |
+   |          |         |           | rows.                    |
+   +----------+---------+-----------+--------------------------+
 
 Multiline table without caption:
 
-+----------+---------+-----------+-------------------------+
-| Centered | Left    | Right     | Default aligned         |
-| Header   | Aligned | Aligned   |                         |
-+==========+=========+===========+=========================+
-| First    | row     | 12.0      | Example of a row that   |
-|          |         |           | spans multiple lines.   |
-+----------+---------+-----------+-------------------------+
-| Second   | row     | 5.0       | Here’s another one.     |
-|          |         |           | Note the blank line     |
-|          |         |           | between rows.           |
-+----------+---------+-----------+-------------------------+
++----------+---------+-----------+--------------------------+
+| Centered | Left    | Right     | Default aligned          |
+| Header   | Aligned | Aligned   |                          |
++==========+=========+===========+==========================+
+| First    | row     | 12.0      | Example of a row that    |
+|          |         |           | spans multiple lines.    |
++----------+---------+-----------+--------------------------+
+| Second   | row     | 5.0       | Here’s another one. Note |
+|          |         |           | the blank line between   |
+|          |         |           | rows.                    |
++----------+---------+-----------+--------------------------+
 
 Table without column headers:
 
@@ -80,11 +80,11 @@
 
 Multiline table without column headers:
 
-+----------+---------+-----------+-------------------------+
-| First    | row     | 12.0      | Example of a row that   |
-|          |         |           | spans multiple lines.   |
-+----------+---------+-----------+-------------------------+
-| Second   | row     | 5.0       | Here’s another one.     |
-|          |         |           | Note the blank line     |
-|          |         |           | between rows.           |
-+----------+---------+-----------+-------------------------+
++----------+---------+-----------+--------------------------+
+| First    | row     | 12.0      | Example of a row that    |
+|          |         |           | spans multiple lines.    |
++----------+---------+-----------+--------------------------+
+| Second   | row     | 5.0       | Here’s another one. Note |
+|          |         |           | the blank line between   |
+|          |         |           | rows.                    |
++----------+---------+-----------+--------------------------+
diff --git a/test/tables.rtf b/test/tables.rtf
--- a/test/tables.rtf
+++ b/test/tables.rtf
@@ -187,7 +187,7 @@
 {\pard \ql \f0 \sa180 \li0 \fi0 Multiline table with caption:\par}
 {
 \trowd \trgaph120
-\clbrdrb\brdrs\cellx1296\clbrdrb\brdrs\cellx2484\clbrdrb\brdrs\cellx3888\clbrdrb\brdrs\cellx6804
+\clbrdrb\brdrs\cellx1296\clbrdrb\brdrs\cellx2484\clbrdrb\brdrs\cellx3888\clbrdrb\brdrs\cellx6912
 \trkeep\intbl
 {
 {{\pard\intbl \qc \f0 \sa0 \li0 \fi0 Centered Header\par}
@@ -202,7 +202,7 @@
 \intbl\row}
 {
 \trowd \trgaph120
-\cellx1296\cellx2484\cellx3888\cellx6804
+\cellx1296\cellx2484\cellx3888\cellx6912
 \trkeep\intbl
 {
 {{\pard\intbl \qc \f0 \sa0 \li0 \fi0 First\par}
@@ -217,7 +217,7 @@
 \intbl\row}
 {
 \trowd \trgaph120
-\cellx1296\cellx2484\cellx3888\cellx6804
+\cellx1296\cellx2484\cellx3888\cellx6912
 \trkeep\intbl
 {
 {{\pard\intbl \qc \f0 \sa0 \li0 \fi0 Second\par}
@@ -234,7 +234,7 @@
 {\pard \ql \f0 \sa180 \li0 \fi0 Multiline table without caption:\par}
 {
 \trowd \trgaph120
-\clbrdrb\brdrs\cellx1296\clbrdrb\brdrs\cellx2484\clbrdrb\brdrs\cellx3888\clbrdrb\brdrs\cellx6804
+\clbrdrb\brdrs\cellx1296\clbrdrb\brdrs\cellx2484\clbrdrb\brdrs\cellx3888\clbrdrb\brdrs\cellx6912
 \trkeep\intbl
 {
 {{\pard\intbl \qc \f0 \sa0 \li0 \fi0 Centered Header\par}
@@ -249,7 +249,7 @@
 \intbl\row}
 {
 \trowd \trgaph120
-\cellx1296\cellx2484\cellx3888\cellx6804
+\cellx1296\cellx2484\cellx3888\cellx6912
 \trkeep\intbl
 {
 {{\pard\intbl \qc \f0 \sa0 \li0 \fi0 First\par}
@@ -264,7 +264,7 @@
 \intbl\row}
 {
 \trowd \trgaph120
-\cellx1296\cellx2484\cellx3888\cellx6804
+\cellx1296\cellx2484\cellx3888\cellx6912
 \trkeep\intbl
 {
 {{\pard\intbl \qc \f0 \sa0 \li0 \fi0 Second\par}
@@ -328,7 +328,7 @@
 {\pard \ql \f0 \sa180 \li0 \fi0 Multiline table without column headers:\par}
 {
 \trowd \trgaph120
-\cellx1296\cellx2484\cellx3888\cellx6804
+\cellx1296\cellx2484\cellx3888\cellx6912
 \trkeep\intbl
 {
 {{\pard\intbl \qc \f0 \sa0 \li0 \fi0 First\par}
@@ -343,7 +343,7 @@
 \intbl\row}
 {
 \trowd \trgaph120
-\cellx1296\cellx2484\cellx3888\cellx6804
+\cellx1296\cellx2484\cellx3888\cellx6912
 \trkeep\intbl
 {
 {{\pard\intbl \qc \f0 \sa0 \li0 \fi0 Second\par}
diff --git a/test/tables.texinfo b/test/tables.texinfo
--- a/test/tables.texinfo
+++ b/test/tables.texinfo
@@ -83,7 +83,7 @@
 Multiline table with caption:
 
 @float
-@multitable @columnfractions 0.15 0.14 0.16 0.34 
+@multitable @columnfractions 0.15 0.14 0.16 0.35 
 @headitem 
 Centered Header
  @tab Left Aligned
@@ -104,7 +104,7 @@
 @end float
 Multiline table without caption:
 
-@multitable @columnfractions 0.15 0.14 0.16 0.34 
+@multitable @columnfractions 0.15 0.14 0.16 0.35 
 @headitem 
 Centered Header
  @tab Left Aligned
@@ -144,7 +144,7 @@
 
 Multiline table without column headers:
 
-@multitable @columnfractions 0.15 0.14 0.16 0.34 
+@multitable @columnfractions 0.15 0.14 0.16 0.35 
 @item 
 First
  @tab row
diff --git a/test/tables.textile b/test/tables.textile
--- a/test/tables.textile
+++ b/test/tables.textile
@@ -80,7 +80,7 @@
 <col width="15%" />
 <col width="13%" />
 <col width="16%" />
-<col width="33%" />
+<col width="35%" />
 <thead>
 <tr class="header">
 <th align="center">Centered Header</th>
@@ -111,7 +111,7 @@
 <col width="15%" />
 <col width="13%" />
 <col width="16%" />
-<col width="33%" />
+<col width="35%" />
 <thead>
 <tr class="header">
 <th align="center">Centered Header</th>
@@ -148,7 +148,7 @@
 <col width="15%" />
 <col width="13%" />
 <col width="16%" />
-<col width="33%" />
+<col width="35%" />
 <tbody>
 <tr class="odd">
 <td align="center">First</td>
diff --git a/test/test-pandoc.hs b/test/test-pandoc.hs
--- a/test/test-pandoc.hs
+++ b/test/test-pandoc.hs
@@ -12,6 +12,7 @@
 import qualified Tests.Readers.Creole
 import qualified Tests.Readers.Docx
 import qualified Tests.Readers.EPUB
+import qualified Tests.Readers.FB2
 import qualified Tests.Readers.HTML
 import qualified Tests.Readers.JATS
 import qualified Tests.Readers.LaTeX
@@ -75,6 +76,7 @@
           , testGroup "EPUB" Tests.Readers.EPUB.tests
           , testGroup "Muse" Tests.Readers.Muse.tests
           , testGroup "Creole" Tests.Readers.Creole.tests
+          , testGroup "FB2" Tests.Readers.FB2.tests
           ]
         , testGroup "Lua filters" Tests.Lua.tests
         ]
diff --git a/test/writer.fb2 b/test/writer.fb2
--- a/test/writer.fb2
+++ b/test/writer.fb2
@@ -22,9 +22,8 @@
 <p>Pandoc Test Suite</p>
 </title>
 <section>
-<p>This is a set of tests for pandoc. Most of them are adapted from John Gruber’s markdown test suite.</p>
-<empty-line />
-<p>——————————</p>
+<p>This is a set of tests for pandoc. Most of them are adapted from
+John Gruber’s markdown test suite.</p>
 <empty-line />
 </section>
 <section>
@@ -33,11 +32,13 @@
 </title>
 <section>
 <title>
-<p>Level 2 with an embedded link &lt;/url&gt;</p>
+<p>Level 2 with an <a l:href="/url">embedded link</a>
+</p>
 </title>
 <section>
 <title>
-<p>Level 3 with emphasis</p>
+<p>Level 3 with <emphasis>emphasis</emphasis>
+</p>
 </title>
 <section>
 <title>
@@ -58,7 +59,8 @@
 </title>
 <section>
 <title>
-<p>Level 2 with emphasis</p>
+<p>Level 2 with <emphasis>emphasis</emphasis>
+</p>
 </title>
 <section>
 <title>
@@ -73,8 +75,6 @@
 </title>
 <p>with no blank line</p>
 <empty-line />
-<p>——————————</p>
-<empty-line />
 </section>
 </section>
 <section>
@@ -82,11 +82,15 @@
 <p>Paragraphs</p>
 </title>
 <p>Here’s a regular paragraph.</p>
-<p>In Markdown 1.0.0 and earlier. Version 8. This line turns into a list item. Because a hard-wrapped line in the middle of a paragraph looked like a list item.</p>
-<p>Here’s one with a bullet. * criminey.</p>
-<p>There should be a hard line break<empty-line />here.</p>
-<empty-line />
-<p>——————————</p>
+<p>In Markdown 1.0.0 and earlier. Version
+8. This line turns into a list item.
+Because a hard-wrapped line in the
+middle of a paragraph looked like a
+list item.</p>
+<p>Here’s one with a bullet.
+* criminey.</p>
+<p>There should be a hard line break
+here.</p>
 <empty-line />
 </section>
 <section>
@@ -95,7 +99,8 @@
 </title>
 <p>E-mail style:</p>
 <cite>
-<p>This is a block quote. It is pretty short.</p>
+<p>This is a block quote.
+It is pretty short.</p>
 </cite>
 <cite>
 <p>Code in a block quote:</p>
@@ -121,11 +126,10 @@
 <p>nested</p>
 </cite>
 </cite>
-<p>This should not be a block quote: 2 &gt; 1.</p>
+<p>This should not be a block quote: 2
+&gt; 1.</p>
 <p>And a following paragraph.</p>
 <empty-line />
-<p>——————————</p>
-<empty-line />
 </section>
 <section>
 <title>
@@ -171,8 +175,6 @@
 </p>
 <empty-line />
 <empty-line />
-<p>——————————</p>
-<empty-line />
 </section>
 <section>
 <title>
@@ -245,7 +247,8 @@
 <p>Multiple paragraphs:</p>
 <p>1. Item 1, graf one.</p>
 <empty-line />
-<p>   Item 1. graf two. The quick brown fox jumped over the lazy dog’s back.</p>
+<p>   Item 1. graf two. The quick brown fox jumped over the lazy dog’s
+back.</p>
 <empty-line />
 <p>2. Item 2.</p>
 <empty-line />
@@ -281,13 +284,17 @@
 <title>
 <p>Tabs and spaces</p>
 </title>
-<p>• this is a list item indented with tabs</p>
+<p>• this is a list item
+indented with tabs</p>
 <empty-line />
-<p>• this is a list item indented with spaces</p>
+<p>• this is a list item
+indented with spaces</p>
 <empty-line />
-<p>• • this is an example list item indented with tabs</p>
+<p>• • this is an example list item
+indented with tabs</p>
 <empty-line />
-<p>• • this is an example list item indented with spaces</p>
+<p>• • this is an example list item
+indented with spaces</p>
 <empty-line />
 </section>
 <section>
@@ -299,7 +306,8 @@
 <empty-line />
 <p>    with a continuation</p>
 <empty-line />
-<p>(3) iv. sublist with roman numerals, starting with 4</p>
+<p>(3) iv. sublist with roman numerals,
+starting with 4</p>
 <p>(3) v. more items</p>
 <p>(3) v. (A) a subsublist</p>
 <p>(3) v. (B) a subsublist</p>
@@ -316,8 +324,6 @@
 <p>M.A. 2007</p>
 <p>B. Williams</p>
 <empty-line />
-<p>——————————</p>
-<empty-line />
 </section>
 </section>
 <section>
@@ -374,7 +380,8 @@
 </p>
 <p>    red fruit</p>
 <empty-line />
-<p>    contains seeds, crisp, pleasant to taste</p>
+<p>    contains seeds,
+crisp, pleasant to taste</p>
 <empty-line />
 <p>
 <strong>
@@ -476,8 +483,6 @@
 <empty-line />
 <p>Hr’s:</p>
 <empty-line />
-<p>——————————</p>
-<empty-line />
 </section>
 <section>
 <title>
@@ -485,9 +490,8 @@
 </title>
 <p>This is <emphasis>emphasized</emphasis>, and so <emphasis>is this</emphasis>.</p>
 <p>This is <strong>strong</strong>, and so <strong>is this</strong>.</p>
-<p>An <emphasis>emphasized link<a l:href="#l1" type="note">
-<sup>[1]</sup>
-</a>
+<p>An <emphasis>
+<a l:href="/url">emphasized link</a>
 </emphasis>.</p>
 <p>
 <strong>
@@ -513,9 +517,8 @@
 <emphasis>hello</emphasis>
 </sup> a<sup>hello there</sup>.</p>
 <p>Subscripts: H<sub>2</sub>O, H<sub>23</sub>O, H<sub>many of them</sub>O.</p>
-<p>These should not be superscripts or subscripts, because of the unescaped spaces: a^b c^d, a~b c~d.</p>
-<empty-line />
-<p>——————————</p>
+<p>These should not be superscripts or subscripts,
+because of the unescaped spaces: a^b c^d, a~b c~d.</p>
 <empty-line />
 </section>
 <section>
@@ -524,17 +527,15 @@
 </title>
 <p>“Hello,” said the spider. “‘Shelob’ is my name.”</p>
 <p>‘A’, ‘B’, and ‘C’ are letters.</p>
-<p>‘Oak,’ ‘elm,’ and ‘beech’ are names of trees. So is ‘pine.’</p>
-<p>‘He said, “I want to go.”’ Were you alive in the 70’s?</p>
-<p>Here is some quoted ‘<code>code</code>’ and a “quoted link<a l:href="#l2" type="note">
-<sup>[2]</sup>
-</a>”.</p>
+<p>‘Oak,’ ‘elm,’ and ‘beech’ are names of trees.
+So is ‘pine.’</p>
+<p>‘He said, “I want to go.”’ Were you alive in the
+70’s?</p>
+<p>Here is some quoted ‘<code>code</code>’ and a “<a l:href="http://example.com/?foo=1&amp;bar=2">quoted link</a>”.</p>
 <p>Some dashes: one—two — three—four — five.</p>
 <p>Dashes between numbers: 5–7, 255–66, 1987–1999.</p>
 <p>Ellipses…and…and….</p>
 <empty-line />
-<p>——————————</p>
-<empty-line />
 </section>
 <section>
 <title>
@@ -550,18 +551,18 @@
 <p>• <code>223</code>
 </p>
 <p>• <code>p</code>-Tree</p>
-<p>• Here’s some display math: <code>\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}</code>
+<p>• Here’s some display math:
+<code>\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}</code>
 </p>
 <p>• Here’s one that has a line break in it: <code>\alpha + \omega \times x^2</code>.</p>
 <p>These shouldn’t be math:</p>
 <p>• To get the famous equation, write <code>$e = mc^2$</code>.</p>
-<p>• $22,000 is a <emphasis>lot</emphasis> of money. So is $34,000. (It worked if “lot” is emphasized.)</p>
+<p>• $22,000 is a <emphasis>lot</emphasis> of money. So is $34,000.
+(It worked if “lot” is emphasized.)</p>
 <p>• Shoes ($20) and socks ($5).</p>
 <p>• Escaped <code>$</code>: $73 <emphasis>this should be emphasized</emphasis> 23$.</p>
 <p>Here’s a LaTeX table:</p>
 <empty-line />
-<p>——————————</p>
-<empty-line />
 </section>
 <section>
 <title>
@@ -595,8 +596,6 @@
 <p>Plus: +</p>
 <p>Minus: -</p>
 <empty-line />
-<p>——————————</p>
-<empty-line />
 </section>
 <section>
 <title>
@@ -606,112 +605,71 @@
 <title>
 <p>Explicit</p>
 </title>
-<p>Just a URL<a l:href="#l3" type="note">
-<sup>[3]</sup>
-</a>.</p>
-<p>URL and title<a l:href="#l4" type="note">
-<sup>[4]</sup>
-</a>.</p>
-<p>URL and title<a l:href="#l5" type="note">
-<sup>[5]</sup>
-</a>.</p>
-<p>URL and title<a l:href="#l6" type="note">
-<sup>[6]</sup>
-</a>.</p>
-<p>URL and title<a l:href="#l7" type="note">
-<sup>[7]</sup>
-</a>
+<p>Just a <a l:href="/url/">URL</a>.</p>
+<p>
+<a l:href="/url/">URL and title</a>.</p>
+<p>
+<a l:href="/url/">URL and title</a>.</p>
+<p>
+<a l:href="/url/">URL and title</a>.</p>
+<p>
+<a l:href="/url/">URL and title</a>
 </p>
-<p>URL and title<a l:href="#l8" type="note">
-<sup>[8]</sup>
-</a>
+<p>
+<a l:href="/url/">URL and title</a>
 </p>
-<p>with_underscore<a l:href="#l9" type="note">
-<sup>[9]</sup>
-</a>
+<p>
+<a l:href="/url/with_underscore">with_underscore</a>
 </p>
-<p>Email link<a l:href="#l10" type="note">
-<sup>[10]</sup>
-</a>
+<p>
+<a l:href="mailto:nobody@nowhere.net">Email link</a>
 </p>
-<p>Empty<a l:href="#l11" type="note">
-<sup>[11]</sup>
-</a>.</p>
+<p>
+<a l:href="">Empty</a>.</p>
 </section>
 <section>
 <title>
 <p>Reference</p>
 </title>
-<p>Foo bar<a l:href="#l12" type="note">
-<sup>[12]</sup>
-</a>.</p>
-<p>With embedded [brackets]<a l:href="#l13" type="note">
-<sup>[13]</sup>
-</a>.</p>
-<p>b<a l:href="#l14" type="note">
-<sup>[14]</sup>
-</a> by itself should be a link.</p>
-<p>Indented once<a l:href="#l15" type="note">
-<sup>[15]</sup>
-</a>.</p>
-<p>Indented twice<a l:href="#l16" type="note">
-<sup>[16]</sup>
-</a>.</p>
-<p>Indented thrice<a l:href="#l17" type="note">
-<sup>[17]</sup>
-</a>.</p>
+<p>Foo <a l:href="/url/">bar</a>.</p>
+<p>With <a l:href="/url/">embedded [brackets]</a>.</p>
+<p>
+<a l:href="/url/">b</a> by itself should be a link.</p>
+<p>Indented <a l:href="/url">once</a>.</p>
+<p>Indented <a l:href="/url">twice</a>.</p>
+<p>Indented <a l:href="/url">thrice</a>.</p>
 <p>This should [not][] be a link.</p>
 <empty-line />
 <p>
 <code>[not]: /url</code>
 </p>
 <empty-line />
-<p>Foo bar<a l:href="#l18" type="note">
-<sup>[18]</sup>
-</a>.</p>
-<p>Foo biz<a l:href="#l19" type="note">
-<sup>[19]</sup>
-</a>.</p>
+<p>Foo <a l:href="/url/">bar</a>.</p>
+<p>Foo <a l:href="/url/">biz</a>.</p>
 </section>
 <section>
 <title>
 <p>With ampersands</p>
 </title>
-<p>Here’s a link with an ampersand in the URL<a l:href="#l20" type="note">
-<sup>[20]</sup>
-</a>.</p>
-<p>Here’s a link with an amersand in the link text: AT&amp;T<a l:href="#l21" type="note">
-<sup>[21]</sup>
-</a>.</p>
-<p>Here’s an inline link<a l:href="#l22" type="note">
-<sup>[22]</sup>
-</a>.</p>
-<p>Here’s an inline link in pointy braces<a l:href="#l23" type="note">
-<sup>[23]</sup>
-</a>.</p>
+<p>Here’s a <a l:href="http://example.com/?foo=1&amp;bar=2">link with an ampersand in the URL</a>.</p>
+<p>Here’s a link with an amersand in the link text: <a l:href="http://att.com/">AT&amp;T</a>.</p>
+<p>Here’s an <a l:href="/script?foo=1&amp;bar=2">inline link</a>.</p>
+<p>Here’s an <a l:href="/script?foo=1&amp;bar=2">inline link in pointy braces</a>.</p>
 </section>
 <section>
 <title>
 <p>Autolinks</p>
 </title>
-<p>With an ampersand: http://example.com/?foo=1&amp;bar=2<a l:href="#l24" type="note">
-<sup>[24]</sup>
-</a>
+<p>With an ampersand: <a l:href="http://example.com/?foo=1&amp;bar=2">http://example.com/?foo=1&amp;bar=2</a>
 </p>
 <p>• In a list?</p>
-<p>• http://example.com/<a l:href="#l25" type="note">
-<sup>[25]</sup>
-</a>
+<p>• <a l:href="http://example.com/">http://example.com/</a>
 </p>
 <p>• It should.</p>
-<p>An e-mail address: nobody@nowhere.net<a l:href="#l26" type="note">
-<sup>[26]</sup>
-</a>
+<p>An e-mail address: <a l:href="mailto:nobody@nowhere.net">nobody@nowhere.net</a>
 </p>
 <cite>
-<p>Blockquoted: http://example.com/<a l:href="#l27" type="note">
-<sup>[27]</sup>
-</a>
+<p>Blockquoted: <a l:href="http://example.com/">http://example.com/</a>
 </p>
 </cite>
 <p>Auto-links should not occur here: <code>&lt;http://example.com/&gt;</code>
@@ -722,8 +680,6 @@
 </p>
 <empty-line />
 <empty-line />
-<p>——————————</p>
-<empty-line />
 </section>
 </section>
 <section>
@@ -734,280 +690,76 @@
 <image l:href="#image1" l:type="imageType" alt="lalune" title="Voyage dans la Lune" />
 <p>Here is a movie <image l:href="#image2" l:type="inlineImageType" alt="movie" /> icon.</p>
 <empty-line />
-<p>——————————</p>
-<empty-line />
 </section>
 <section>
 <title>
 <p>Footnotes</p>
 </title>
-<p>Here is a footnote reference,<a l:href="#n28" type="note">
-<sup>[28]</sup>
-</a> and another.<a l:href="#n29" type="note">
-<sup>[29]</sup>
-</a> This should <emphasis>not</emphasis> be a footnote reference, because it contains a space.[^my note] Here is an inline note.<a l:href="#n30" type="note">
-<sup>[30]</sup>
+<p>Here is a footnote reference,<a l:href="#n1" type="note">
+<sup>[1]</sup>
+</a> and another.<a l:href="#n2" type="note">
+<sup>[2]</sup>
 </a>
+This should <emphasis>not</emphasis> be a footnote reference, because it
+contains a space.[^my note] Here is an inline note.<a l:href="#n3" type="note">
+<sup>[3]</sup>
+</a>
 </p>
 <cite>
-<p>Notes can go in quotes.<a l:href="#n31" type="note">
-<sup>[31]</sup>
+<p>Notes can go in quotes.<a l:href="#n4" type="note">
+<sup>[4]</sup>
 </a>
 </p>
 </cite>
-<p>1. And in list items.<a l:href="#n32" type="note">
-<sup>[32]</sup>
+<p>1. And in list items.<a l:href="#n5" type="note">
+<sup>[5]</sup>
 </a>
 </p>
 <p>This paragraph should not be part of the note, as it is not indented.</p>
 </section>
 </body>
 <body name="notes">
-<section id="l1">
+<section id="n1">
 <title>
 <p>1</p>
 </title>
-<p>
-<code>/url</code>
-</p>
+<p>Here is the footnote. It can go anywhere after the footnote
+reference. It need not be placed at the end of the document.</p>
 </section>
-<section id="l2">
+<section id="n2">
 <title>
 <p>2</p>
 </title>
-<p>
-<code>http://example.com/?foo=1&amp;bar=2</code>
-</p>
-</section>
-<section id="l3">
-<title>
-<p>3</p>
-</title>
-<p>
-<code>/url/</code>
-</p>
-</section>
-<section id="l4">
-<title>
-<p>4</p>
-</title>
-<p>title: <code>/url/</code>
-</p>
-</section>
-<section id="l5">
-<title>
-<p>5</p>
-</title>
-<p>title preceded by two spaces: <code>/url/</code>
-</p>
-</section>
-<section id="l6">
-<title>
-<p>6</p>
-</title>
-<p>title preceded by a tab: <code>/url/</code>
-</p>
-</section>
-<section id="l7">
-<title>
-<p>7</p>
-</title>
-<p>title with &quot;quotes&quot; in it: <code>/url/</code>
-</p>
-</section>
-<section id="l8">
-<title>
-<p>8</p>
-</title>
-<p>title with single quotes: <code>/url/</code>
-</p>
-</section>
-<section id="l9">
-<title>
-<p>9</p>
-</title>
-<p>
-<code>/url/with_underscore</code>
-</p>
-</section>
-<section id="l10">
-<title>
-<p>10</p>
-</title>
-<p>
-<code>mailto:nobody@nowhere.net</code>
-</p>
-</section>
-<section id="l11">
-<title>
-<p>11</p>
-</title>
-<p>
-<code>
-</code>
-</p>
-</section>
-<section id="l12">
-<title>
-<p>12</p>
-</title>
-<p>
-<code>/url/</code>
-</p>
-</section>
-<section id="l13">
-<title>
-<p>13</p>
-</title>
-<p>
-<code>/url/</code>
-</p>
-</section>
-<section id="l14">
-<title>
-<p>14</p>
-</title>
-<p>
-<code>/url/</code>
-</p>
-</section>
-<section id="l15">
-<title>
-<p>15</p>
-</title>
-<p>
-<code>/url</code>
-</p>
-</section>
-<section id="l16">
-<title>
-<p>16</p>
-</title>
-<p>
-<code>/url</code>
-</p>
-</section>
-<section id="l17">
-<title>
-<p>17</p>
-</title>
-<p>
-<code>/url</code>
-</p>
-</section>
-<section id="l18">
-<title>
-<p>18</p>
-</title>
-<p>Title with &quot;quotes&quot; inside: <code>/url/</code>
-</p>
-</section>
-<section id="l19">
-<title>
-<p>19</p>
-</title>
-<p>Title with &quot;quote&quot; inside: <code>/url/</code>
-</p>
-</section>
-<section id="l20">
-<title>
-<p>20</p>
-</title>
-<p>
-<code>http://example.com/?foo=1&amp;bar=2</code>
-</p>
-</section>
-<section id="l21">
-<title>
-<p>21</p>
-</title>
-<p>AT&amp;T: <code>http://att.com/</code>
-</p>
-</section>
-<section id="l22">
-<title>
-<p>22</p>
-</title>
-<p>
-<code>/script?foo=1&amp;bar=2</code>
-</p>
-</section>
-<section id="l23">
-<title>
-<p>23</p>
-</title>
-<p>
-<code>/script?foo=1&amp;bar=2</code>
-</p>
-</section>
-<section id="l24">
-<title>
-<p>24</p>
-</title>
-<p>
-<code>http://example.com/?foo=1&amp;bar=2</code>
-</p>
-</section>
-<section id="l25">
-<title>
-<p>25</p>
-</title>
-<p>
-<code>http://example.com/</code>
-</p>
-</section>
-<section id="l26">
-<title>
-<p>26</p>
-</title>
-<p>
-<code>mailto:nobody@nowhere.net</code>
-</p>
-</section>
-<section id="l27">
-<title>
-<p>27</p>
-</title>
-<p>
-<code>http://example.com/</code>
-</p>
-</section>
-<section id="n28">
-<title>
-<p>28</p>
-</title>
-<p>Here is the footnote. It can go anywhere after the footnote reference. It need not be placed at the end of the document.</p>
-</section>
-<section id="n29">
-<title>
-<p>29</p>
-</title>
-<p>Here’s the long note. This one contains multiple blocks.</p>
-<p>Subsequent blocks are indented to show that they belong to the footnote (as with list items).</p>
+<p>Here’s the long note. This one contains multiple
+blocks.</p>
+<p>Subsequent blocks are indented to show that they belong to the
+footnote (as with list items).</p>
 <empty-line />
 <p>
 <code>  { &lt;code&gt; }</code>
 </p>
 <empty-line />
-<p>If you want, you can indent every line, but you can also be lazy and just indent the first line of each block.</p>
+<p>If you want, you can indent every line, but you can also be
+lazy and just indent the first line of each block.</p>
 </section>
-<section id="n30">
+<section id="n3">
 <title>
-<p>30</p>
+<p>3</p>
 </title>
-<p>This is <emphasis>easier</emphasis> to type. Inline notes may contain links<a l:href="#l30" type="note">
-<sup>[30]</sup>
-</a> and <code>]</code> verbatim characters, as well as [bracketed text].</p>
+<p>This
+is <emphasis>easier</emphasis> to type. Inline notes may contain
+<a l:href="http://google.com">links</a> and <code>]</code> verbatim characters,
+as well as [bracketed text].</p>
 </section>
-<section id="n31">
+<section id="n4">
 <title>
-<p>31</p>
+<p>4</p>
 </title>
 <p>In quote.</p>
 </section>
-<section id="n32">
+<section id="n5">
 <title>
-<p>32</p>
+<p>5</p>
 </title>
 <p>In list.</p>
 </section>
diff --git a/test/writer.ms b/test/writer.ms
--- a/test/writer.ms
+++ b/test/writer.ms
@@ -67,12 +67,15 @@
 John MacFarlane
 .AU
 Anonymous
-.ND "July 17, 2006"
+.AU
+.sp 0.5
+.ft R
+July 17, 2006
 .\" 1 column (use .2C for two column)
 .1C
 .LP
 This is a set of tests for pandoc.
-Most of them are adapted from John Gruber's markdown test suite.
+Most of them are adapted from John Gruber’s markdown test suite.
 .HLINE
 .SH 1
 Headers
@@ -86,7 +89,7 @@
 .pdfhref O 2 "Level 2 with an embedded link"
 .pdfhref M "level-2-with-an-embedded-link"
 .SH 3
-Level 3 with \f[I]emphasis\f[]
+Level 3 with \f[BI]emphasis\f[B]
 .pdfhref O 3 "Level 3 with emphasis"
 .pdfhref M "level-3-with-emphasis"
 .SH 4
@@ -102,7 +105,7 @@
 .pdfhref O 1 "Level 1"
 .pdfhref M "level-1"
 .SH 2
-Level 2 with \f[I]emphasis\f[]
+Level 2 with \f[BI]emphasis\f[B]
 .pdfhref O 2 "Level 2 with emphasis"
 .pdfhref M "level-2-with-emphasis"
 .SH 3
@@ -123,7 +126,7 @@
 .pdfhref O 1 "Paragraphs"
 .pdfhref M "paragraphs"
 .LP
-Here's a regular paragraph.
+Here’s a regular paragraph.
 .PP
 In Markdown 1.0.0 and earlier.
 Version 8.
@@ -131,7 +134,7 @@
 Because a hard-wrapped line in the middle of a paragraph looked like a list
 item.
 .PP
-Here's one with a bullet.
+Here’s one with a bullet.
 * criminey.
 .PP
 There should be a hard line break
@@ -311,7 +314,7 @@
 .PP
 Item 1.
 graf two.
-The quick brown fox jumped over the lazy dog's back.
+The quick brown fox jumped over the lazy dog’s back.
 .RE
 .IP " 2." 4
 Item 2.
@@ -332,7 +335,7 @@
 .RE
 .RE
 .LP
-Here's another:
+Here’s another:
 .IP " 1." 4
 First
 .IP " 2." 4
@@ -481,13 +484,13 @@
 .RE
 .LP
 Multiple blocks with italics:
-.IP "\f[I]apple\f[]"
+.IP "\f[I]apple\f[R]"
 red fruit
 .RS
 .PP
 contains seeds, crisp, pleasant to taste
 .RE
-.IP "\f[I]orange\f[]"
+.IP "\f[I]orange\f[R]"
 orange fruit
 .RS
 .IP
@@ -564,10 +567,10 @@
 bar
 .LP
 Interpreted markdown in a table:
-This is \f[I]emphasized\f[]
-And this is \f[B]strong\f[]
+This is \f[I]emphasized\f[R]
+And this is \f[B]strong\f[R]
 .PP
-Here's a simple block:
+Here’s a simple block:
 .LP
 foo
 .LP
@@ -614,36 +617,36 @@
 \f[]
 .fi
 .LP
-Hr's:
+Hr’s:
 .HLINE
 .SH 1
 Inline Markup
 .pdfhref O 1 "Inline Markup"
 .pdfhref M "inline-markup"
 .LP
-This is \f[I]emphasized\f[], and so \f[I]is this\f[].
+This is \f[I]emphasized\f[R], and so \f[I]is this\f[R].
 .PP
-This is \f[B]strong\f[], and so \f[B]is this\f[].
+This is \f[B]strong\f[R], and so \f[B]is this\f[R].
 .PP
 An \f[I]\c
 .pdfhref W -D "/url" -A "\c" \
  -- "emphasized link"
-\&\f[].
+\&\f[R].
 .PP
-\f[B]\f[BI]This is strong and em.\f[B]\f[]
+\f[B]\f[BI]This is strong and em.\f[B]\f[R]
 .PP
-So is \f[B]\f[BI]this\f[B]\f[] word.
+So is \f[B]\f[BI]this\f[B]\f[R] word.
 .PP
-\f[B]\f[BI]This is strong and em.\f[B]\f[]
+\f[B]\f[BI]This is strong and em.\f[B]\f[R]
 .PP
-So is \f[B]\f[BI]this\f[B]\f[] word.
+So is \f[B]\f[BI]this\f[B]\f[R] word.
 .PP
-This is code: \f[C]>\f[], \f[C]$\f[], \f[C]\\\f[], \f[C]\\$\f[],
-\f[C]<html>\f[].
+This is code: \f[C]>\f[R], \f[C]$\f[R], \f[C]\\\f[R], \f[C]\\$\f[R],
+\f[C]<html>\f[R].
 .PP
-\m[strikecolor]This is \f[I]strikeout\f[].\m[]
+\m[strikecolor]This is \f[I]strikeout\f[R].\m[]
 .PP
-Superscripts: a\*{bc\*}d a\*{\f[I]hello\f[]\*} a\*{hello\~there\*}.
+Superscripts: a\*{bc\*}d a\*{\f[I]hello\f[R]\*} a\*{hello\~there\*}.
 .PP
 Subscripts: H\*<2\*>O, H\*<23\*>O, H\*<many\~of\~them\*>O.
 .PP
@@ -663,9 +666,9 @@
 `Oak,' `elm,' and `beech' are names of trees.
 So is `pine.'
 .PP
-`He said, \[lq]I want to go.\[rq]' Were you alive in the 70's?
+`He said, \[lq]I want to go.\[rq]' Were you alive in the 70’s?
 .PP
-Here is some quoted `\f[C]code\f[]' and a \[lq]\c
+Here is some quoted `\f[C]code\f[R]' and a \[lq]\c
 .pdfhref W -D "http://example.com/?foo=1&bar=2" -A "\c" \
  -- "quoted link"
 \&\[rq].
@@ -692,26 +695,26 @@
 .IP \[bu] 3
 @p@-Tree
 .IP \[bu] 3
-Here's some display math:
+Here’s some display math:
 .EQ
 d over {d x} f ( x ) = lim sub {h -> 0} {f ( x + h ) \[u2212] f ( x )} over h
 .EN
 .IP \[bu] 3
-Here's one that has a line break in it: @alpha + omega times x sup 2@.
+Here’s one that has a line break in it: @alpha + omega times x sup 2@.
 .LP
-These shouldn't be math:
+These shouldn’t be math:
 .IP \[bu] 3
-To get the famous equation, write \f[C]$e\ =\ mc\[ha]2$\f[].
+To get the famous equation, write \f[C]$e\ =\ mc\[ha]2$\f[R].
 .IP \[bu] 3
-$22,000 is a \f[I]lot\f[] of money.
+$22,000 is a \f[I]lot\f[R] of money.
 So is $34,000.
 (It worked if \[lq]lot\[rq] is emphasized.)
 .IP \[bu] 3
 Shoes ($20) and socks ($5).
 .IP \[bu] 3
-Escaped \f[C]$\f[]: $73 \f[I]this should be emphasized\f[] 23$.
+Escaped \f[C]$\f[R]: $73 \f[I]this should be emphasized\f[R] 23$.
 .LP
-Here's a LaTeX table:
+Here’s a LaTeX table:
 .HLINE
 .SH 1
 Special Characters
@@ -882,22 +885,22 @@
 .pdfhref O 2 "With ampersands"
 .pdfhref M "with-ampersands"
 .LP
-Here's a \c
+Here’s a \c
 .pdfhref W -D "http://example.com/?foo=1&bar=2" -A "\c" \
  -- "link with an ampersand in the URL"
 \&.
 .PP
-Here's a link with an amersand in the link text: \c
+Here’s a link with an amersand in the link text: \c
 .pdfhref W -D "http://att.com/" -A "\c" \
  -- "AT&T"
 \&.
 .PP
-Here's an \c
+Here’s an \c
 .pdfhref W -D "/script?foo=1&bar=2" -A "\c" \
  -- "inline link"
 \&.
 .PP
-Here's an \c
+Here’s an \c
 .pdfhref W -D "/script?foo=1&bar=2" -A "\c" \
  -- "inline link in pointy braces"
 \&.
@@ -932,7 +935,7 @@
 \&
 .RE
 .LP
-Auto-links should not occur here: \f[C]<http://example.com/>\f[]
+Auto-links should not occur here: \f[C]<http://example.com/>\f[R]
 .IP
 .nf
 \f[C]
@@ -964,7 +967,7 @@
 .FE
 and another.\**
 .FS
-Here's the long note.
+Here’s the long note.
 This one contains multiple blocks.
 .PP
 Subsequent blocks are indented to show that they belong to the footnote (as
@@ -979,14 +982,14 @@
 If you want, you can indent every line, but you can also be lazy and just
 indent the first line of each block.
 .FE
-This should \f[I]not\f[] be a footnote reference, because it contains a
+This should \f[I]not\f[R] be a footnote reference, because it contains a
 space.[\[ha]my note] Here is an inline note.\**
 .FS
-This is \f[I]easier\f[] to type.
+This is \f[I]easier\f[R] to type.
 Inline notes may contain \c
 .pdfhref W -D "http://google.com" -A "\c" \
  -- "links"
-\& and \f[C]]\f[] verbatim characters, as well as [bracketed text].
+\& and \f[C]]\f[R] verbatim characters, as well as [bracketed text].
 .FE
 .RS
 .LP
diff --git a/test/writer.muse b/test/writer.muse
--- a/test/writer.muse
+++ b/test/writer.muse
@@ -79,7 +79,7 @@
 </quote>
 </quote>
 
-This should not be a block quote: 2 <verbatim>></verbatim> 1.
+This should not be a block quote: 2 > 1.
 
 And a following paragraph.
 
@@ -224,9 +224,9 @@
     with a continuation
 
     iv. sublist with roman numerals, starting with 4
-    v.  more items
-        A. a subsublist
-        B. a subsublist
+    v. more items
+       A. a subsublist
+       B. a subsublist
 
 Nesting:
 
@@ -562,7 +562,7 @@
 
 4 <verbatim><</verbatim> 5.
 
-6 <verbatim>></verbatim> 5.
+6 > 5.
 
 Backslash: \
 
@@ -576,15 +576,15 @@
 
 Right brace: }
 
-Left bracket: <verbatim>[</verbatim>
+Left bracket: [
 
-Right bracket: <verbatim>]</verbatim>
+Right bracket: ]
 
 Left paren: (
 
 Right paren: )
 
-Greater-than: <verbatim>></verbatim>
+Greater-than: >
 
 Hash: <verbatim>#</verbatim>
 
@@ -594,7 +594,7 @@
 
 Plus: +
 
-Minus: <verbatim>-</verbatim>
+Minus: -
 
 ----
 
@@ -634,7 +634,7 @@
 
 Indented [[/url][thrice]].
 
-This should <verbatim>[not][]</verbatim> be a link.
+This should [not][] be a link.
 
 <example>
 [not]: /url
@@ -690,8 +690,8 @@
 * Footnotes
 
 Here is a footnote reference,[1] and another.[2] This should <em>not</em> be a
-footnote reference, because it contains a <verbatim>space.[^my</verbatim>
-<verbatim>note]</verbatim> Here is an inline note.[3]
+footnote reference, because it contains a space.[^my note] Here is an inline
+note.[3]
 
 <quote>
 Notes can go in quotes.[4]
@@ -718,7 +718,7 @@
 
 [3] This is <em>easier</em> to type. Inline notes may contain
     [[http://google.com][links]] and <code>]</code> verbatim characters, as
-    well as <verbatim>[bracketed</verbatim> <verbatim>text].</verbatim>
+    well as [bracketed text].
 
 [4] In quote.
 
diff --git a/test/writer.rst b/test/writer.rst
--- a/test/writer.rst
+++ b/test/writer.rst
@@ -69,30 +69,30 @@
 
 E-mail style:
 
-    This is a block quote. It is pretty short.
+   This is a block quote. It is pretty short.
 
 ..
 
-    Code in a block quote:
+   Code in a block quote:
 
-    ::
+   ::
 
-        sub status {
-            print "working";
-        }
+      sub status {
+          print "working";
+      }
 
-    A list:
+   A list:
 
-    1. item one
-    2. item two
+   1. item one
+   2. item two
 
-    Nested block quotes:
+   Nested block quotes:
 
-        nested
+      nested
 
-    ..
+   ..
 
-        nested
+      nested
 
 This should not be a block quote: 2 > 1.
 
@@ -107,21 +107,21 @@
 
 ::
 
-    ---- (should be four hyphens)
+   ---- (should be four hyphens)
 
-    sub status {
-        print "working";
-    }
+   sub status {
+       print "working";
+   }
 
-    this code block is indented by one tab
+   this code block is indented by one tab
 
 And:
 
 ::
 
-        this code block is indented by two tabs
+       this code block is indented by two tabs
 
-    These should not be escaped:  \$ \\ \> \[ \{
+   These should not be escaped:  \$ \\ \> \[ \{
 
 --------------
 
@@ -302,83 +302,83 @@
 Tight using spaces:
 
 apple
-    red fruit
+   red fruit
 orange
-    orange fruit
+   orange fruit
 banana
-    yellow fruit
+   yellow fruit
 
 Tight using tabs:
 
 apple
-    red fruit
+   red fruit
 orange
-    orange fruit
+   orange fruit
 banana
-    yellow fruit
+   yellow fruit
 
 Loose:
 
 apple
-    red fruit
+   red fruit
 
 orange
-    orange fruit
+   orange fruit
 
 banana
-    yellow fruit
+   yellow fruit
 
 Multiple blocks with italics:
 
 *apple*
-    red fruit
+   red fruit
 
-    contains seeds, crisp, pleasant to taste
+   contains seeds, crisp, pleasant to taste
 
 *orange*
-    orange fruit
+   orange fruit
 
-    ::
+   ::
 
-        { orange code block }
+      { orange code block }
 
-    ..
+   ..
 
-        orange block quote
+      orange block quote
 
 Multiple definitions, tight:
 
 apple
-    red fruit
-    computer
+   red fruit
+   computer
 orange
-    orange fruit
-    bank
+   orange fruit
+   bank
 
 Multiple definitions, loose:
 
 apple
-    red fruit
+   red fruit
 
-    computer
+   computer
 
 orange
-    orange fruit
+   orange fruit
 
-    bank
+   bank
 
 Blank line after term, indented marker, alternate markers:
 
 apple
-    red fruit
+   red fruit
 
-    computer
+   computer
 
 orange
-    orange fruit
+   orange fruit
 
-    1. sublist
-    2. sublist
+   1. sublist
+   2. sublist
 
 HTML Blocks
 ===========
@@ -491,15 +491,15 @@
 
 ::
 
-    <div>
-        foo
-    </div>
+   <div>
+       foo
+   </div>
 
 As should this:
 
 ::
 
-    <div>foo</div>
+   <div>foo</div>
 
 Now, nested:
 
@@ -554,7 +554,7 @@
 
 ::
 
-    <!-- Comment -->
+   <!-- Comment -->
 
 Just plain comment, with trailing spaces on the line:
 
@@ -566,7 +566,7 @@
 
 ::
 
-    <hr />
+   <hr />
 
 Hr’s:
 
@@ -615,21 +615,21 @@
 
 This is **strong**, and so **is this**.
 
-An *`emphasized link </url>`__*.
+An `emphasized link </url>`__.
 
-***This is strong and em.***
+**This is strong and em.**
 
-So is ***this*** word.
+So is **this** word.
 
-***This is strong and em.***
+**This is strong and em.**
 
-So is ***this*** word.
+So is **this** word.
 
 This is code: ``>``, ``$``, ``\``, ``\$``, ``<html>``.
 
-[STRIKEOUT:This is *strikeout*.]
+[STRIKEOUT:This is strikeout.]
 
-Superscripts: a\ :sup:`bc`\ d a\ :sup:`*hello*` a\ :sup:`hello there`.
+Superscripts: a\ :sup:`bc`\ d a\ :sup:`hello` a\ :sup:`hello there`.
 
 Subscripts: H\ :sub:`2`\ O, H\ :sub:`23`\ O, H\ :sub:`many of them`\ O.
 
@@ -793,7 +793,7 @@
 
 ::
 
-    [not]: /url
+   [not]: /url
 
 Foo `bar </url/>`__.
 
@@ -822,13 +822,13 @@
 
 An e-mail address: nobody@nowhere.net
 
-    Blockquoted: http://example.com/
+   Blockquoted: http://example.com/
 
 Auto-links should not occur here: ``<http://example.com/>``
 
 ::
 
-    or here: <http://example.com/>
+   or here: <http://example.com/>
 
 --------------
 
@@ -853,7 +853,7 @@
 footnote reference, because it contains a space.[^my note] Here is an inline
 note. [3]_
 
-    Notes can go in quotes. [4]_
+   Notes can go in quotes. [4]_
 
 1. And in list items. [5]_
 
@@ -871,7 +871,7 @@
 
    ::
 
-         { <code> }
+        { <code> }
 
    If you want, you can indent every line, but you can also be lazy and just
    indent the first line of each block.
