diff --git a/AUTHORS.md b/AUTHORS.md
--- a/AUTHORS.md
+++ b/AUTHORS.md
@@ -95,6 +95,7 @@
 - Jesse Rosenthal
 - Joe Hermaszewski
 - Joe Hillenbrand
+- John KetzerX
 - John MacFarlane
 - John Muccigrosso
 - John Luke Bentley
@@ -176,6 +177,7 @@
 - Simon Hengel
 - Stefan Dresselhaus
 - Sumit Sahrawat
+- Tarik Graba
 - Thenaesh Elango
 - Thomas Hodgson
 - Thomas Weißschuh
diff --git a/COPYRIGHT b/COPYRIGHT
--- a/COPYRIGHT
+++ b/COPYRIGHT
@@ -1,5 +1,5 @@
 Pandoc
-Copyright (C) 2006-2018 John MacFarlane <jgm at berkeley dot edu>
+Copyright (C) 2006-2019 John MacFarlane <jgm at berkeley dot edu>
 
 With the exceptions noted below, this code is released under the [GPL],
 version 2 or later:
@@ -37,7 +37,7 @@
 Text.Pandoc.Builder, Text.Pandoc.Generics, Text.Pandoc.JSON,
 Text.Pandoc.Walk) are licensed under the BSD 3-clause license:
 
-Copyright (c) 2006-2018, John MacFarlane
+Copyright (c) 2006-2019, John MacFarlane
 
 All rights reserved.
 
@@ -73,29 +73,29 @@
 GPL (v2 or higher, same as pandoc) or (at your option) the BSD
 3-clause license.
 
-Copyright (c) 2014--2018, John MacFarlane
+Copyright (c) 2014--2019, John MacFarlane
 
 ----------------------------------------------------------------------
 src/Text/Pandoc/Writers/Muse.hs
-Copyright (C) 2017-2018 Alexander Krotov
+Copyright (C) 2017-2019 Alexander Krotov
 
 Released under the GNU General Public License version 2 or later.
 
 ----------------------------------------------------------------------
 src/Text/Pandoc/Writers/Texinfo.hs
-Copyright (C) 2008-2018 John MacFarlane and Peter Wang
+Copyright (C) 2008-2019 John MacFarlane and Peter Wang
 
 Released under the GNU General Public License version 2 or later.
 
 ----------------------------------------------------------------------
 src/Text/Pandoc/Writers/OpenDocument.hs
-Copyright (C) 2008-2018 Andrea Rossato and John MacFarlane
+Copyright (C) 2008-2019 Andrea Rossato and John MacFarlane
 
 Released under the GNU General Public License version 2 or later.
 
 ----------------------------------------------------------------------
 src/Text/Pandoc/Writers/Org.hs
-Copyright (C) 2010-2018 Puneeth Chaganti, John MacFarlane, and
+Copyright (C) 2010-2019 Puneeth Chaganti, John MacFarlane, and
                         Albert Krewinkel
 
 Released under the GNU General Public License version 2 or later.
@@ -109,13 +109,13 @@
 ----------------------------------------------------------------------
 src/Text/Pandoc/Readers/Docx.hs
 src/Text/Pandoc/Readers/Docx/*
-Copyright (C) 2014-2018 Jesse Rosenthal
+Copyright (C) 2014-2019 Jesse Rosenthal
 
 Released under the GNU General Public License version 2 or later.
 
 ----------------------------------------------------------------------
 src/Text/Pandoc/Readers/Textile.hs
-Copyright (C) 2010-2018 Paul Rivier and John MacFarlane
+Copyright (C) 2010-2019 Paul Rivier and John MacFarlane
 
 Released under the GNU General Public License version 2 or later.
 
@@ -141,7 +141,7 @@
 src/Text/Pandoc/Readers/Org.hs
 src/Text/Pandoc/Readers/Org/*
 test/Tests/Readers/Org/*
-Copyright (C) 2014-2018 Albert Krewinkel
+Copyright (C) 2014-2019 Albert Krewinkel
 
 Released under the GNU General Public License version 2 or later.
 
@@ -153,7 +153,7 @@
 
 ----------------------------------------------------------------------
 data/pandoc.lua
-Copyright (C) 2017-2018 Albert Krewinkel
+Copyright (C) 2017-2019 Albert Krewinkel
 
 Released under the GNU General Public License version 2 or later.
 
diff --git a/MANUAL.txt b/MANUAL.txt
--- a/MANUAL.txt
+++ b/MANUAL.txt
@@ -1,6 +1,6 @@
 % Pandoc User's Guide
 % John MacFarlane
-% January 30, 2019
+% March 2, 2019
 
 Synopsis
 ========
@@ -279,7 +279,7 @@
 :   Specify output format.  *FORMAT* can be:
 
     ::: {#output-formats}
-    - `asciidoc` ([AsciiDoc])
+    - `asciidoc` ([AsciiDoc]) or `asciidoctor` ([AsciiDoctor])
     - `beamer` ([LaTeX beamer][`beamer`] slide show)
     - `commonmark` ([CommonMark] Markdown)
     - `context` ([ConTeXt])
@@ -349,18 +349,13 @@
 
 :   Specify the user data directory to search for pandoc data files.
     If this option is not specified, the default user data directory
-    will be used.  This is, in UNIX:
-
-        $HOME/.pandoc
-
-    in Windows XP:
-
-        C:\Documents And Settings\USERNAME\Application Data\pandoc
-
-    and in Windows Vista or later:
-
-        C:\Users\USERNAME\AppData\Roaming\pandoc
-
+    will be used.  On \*nix and macOS systems this will be the `pandoc`
+    subdirectory of the XDG data directory (by default,
+    `$HOME/.local/share`, overridable by setting the `XDG_DATA_HOME`
+    environment variable).  If that directory does not exist,
+    `$HOME/.pandoc` will be used (for backwards compatibility).
+    In Windows the default user data directory is
+    `C:\Users\USERNAME\AppData\Roaming\pandoc`.
     You can find the default user data directory on your system by
     looking at the output of `pandoc --version`.
     A `reference.odt`, `reference.docx`, `epub.css`, `templates`,
@@ -465,6 +460,7 @@
 [GNU Texinfo]: http://www.gnu.org/software/texinfo/
 [Emacs Org mode]: http://orgmode.org
 [AsciiDoc]: http://www.methods.co.nz/asciidoc/
+[AsciiDoctor]: https://asciidoctor.org/
 [DZSlides]: http://paulrouget.com/dzslides/
 [Word docx]: https://en.wikipedia.org/wiki/Office_Open_XML
 [PDF]: https://www.adobe.com/pdf/
@@ -1025,9 +1021,9 @@
         in Word, modify the styles as you wish, and save the file.
         For best results, do not make changes to this file other
         than modifying the styles used by pandoc:
-        
+
         Paragraph styles:
-        
+
         - Normal
         - Body Text
         - First Paragraph
@@ -1057,17 +1053,17 @@
         - Figure
         - Captioned Figure
         - TOC Heading
-        
+
         Character styles:
-        
+
         - Default Paragraph Font
         - Body Text Char
         - Verbatim Char
         - Footnote Reference
         - Hyperlink
-        
+
         Table style:
-        
+
         - Table
 
     ODT
@@ -1191,17 +1187,29 @@
     the EPUB-specific contents.  The default is `EPUB`.  To put
     the EPUB contents in the top level, use an empty string.
 
-`--pdf-engine=pdflatex`|`lualatex`|`xelatex`|`wkhtmltopdf`|`weasyprint`|`prince`|`context`|`pdfroff`
+`--ipynb-output=all|none|best`
 
+:   Determines how ipynb output cells are treated. `all` means
+    that all of the data formats included in the original are
+    preserved.  `none` means that the contents of data cells
+    are omitted.  `best` causes pandoc to try to pick the
+    richest data block in each output cell that is compatible
+    with the output format.  The default is `best`.
+
+`--pdf-engine=`*PROGRAM*
+
 :   Use the specified engine when producing PDF output.
+    Valid values are `pdflatex`, `lualatex`, `xelatex`, `latexmk`,
+    `wkhtmltopdf`, `weasyprint`, `prince`, `context`, and `pdfroff`.
     The default is `pdflatex`.  If the engine is not in your PATH,
     the full path of the engine may be specified here.
 
 `--pdf-engine-opt=`*STRING*
 
 :   Use the given string as a command-line argument to the `pdf-engine`.
-    If used multiple times, the arguments are provided with spaces between
-    them. Note that no check for duplicate options is done.
+    For example, to use a persistent directory `foo` for `latexmk`'s
+    auxiliary files, use `--pdf-engine-opt=-outdir=foo`.
+    Note that no check for duplicate options is done.
 
 [Dublin Core elements]: http://dublincore.org/documents/dces/
 [ISO 8601 format]: http://www.w3.org/TR/NOTE-datetime
@@ -1393,7 +1401,7 @@
     and AsciiDoc metadata; repeat as for `author`, above
 
 `subject`
-:   document subject, included in ODT, docx and pptx metadata
+:   document subject, included in ODT, PDF, docx and pptx metadata
 
 `description`
 :   document description, included in ODT, docx and pptx metadata. Some
@@ -1433,10 +1441,10 @@
     The [Language subtag lookup] tool can look up or verify these tags.
     This affects most formats, and controls hyphenation in PDF output
     when using LaTeX (through [`babel`] and [`polyglossia`]) or ConTeXt.
-    
+
     Use native pandoc [Divs and Spans] with the `lang` attribute to
     switch the language:
-    
+
         ---
         lang: en-GB
         ...
@@ -1448,7 +1456,7 @@
         :::
 
         More text in English. ['Zitat auf Deutsch.']{lang=de}
-    
+
 `dir`
 :   the base script direction, either `rtl` (right-to-left)
     or `ltr` (left-to-right).
@@ -1588,7 +1596,7 @@
 :   options for package used as `fontfamily`; repeat for multiple options.
     For example, to use the Libertine font with proportional lowercase
     (old-style) figures through the [`libertinus`] package:
-    
+
         ---
         fontfamily: libertinus
         fontfamilyoptions:
@@ -1924,6 +1932,8 @@
 
     $author.name$ ($author.affiliation$)
 
+The value of a variable will be indented to the same level as the variable.
+
 If you use custom templates, you may need to revise them as pandoc
 changes.  We recommend tracking the changes in the default templates,
 and modifying your custom templates accordingly. An easy way to do this
@@ -2215,10 +2225,11 @@
 
 #### Extension: `styles` #### {#ext-styles}
 
-Read all docx styles as divs (for paragraph styles) and spans (for
-character styles) regardless of whether pandoc understands the meaning
-of these styles. This can be used with [docx custom
-styles](#custom-styles). Disabled by default.
+When converting from docx, read all docx styles as divs (for
+paragraph styles) and spans (for character styles) regardless
+of whether pandoc understands the meaning of these styles.
+This can be used with [docx custom styles](#custom-styles).
+Disabled by default.
 
 input formats
 :  `docx`
@@ -3513,7 +3524,11 @@
   ~ It will be rendered using an [interpreted text role `:math:`].
 
 AsciiDoc
-  ~ It will be rendered as `latexmath:[...]`.
+  ~ For AsciiDoc output format (`-t asciidoc`) it will appear verbatim
+    surrounded by `latexmath:[$...$]` (for inline math) or
+    `[latexmath]++++\[...\]+++` (for display math).
+    For AsciiDoctor output format (`-t asciidoctor`) the LaTex delimiters
+    (`$..$` and `\[..\]`) are omitted.
 
 Texinfo
   ~ It will be rendered inside a `@math` command.
@@ -4535,9 +4550,9 @@
   * Headers *above* the slide level in the hierarchy create
     "title slides," which just contain the section title
     and help to break the slide show into sections.
-
-  * Content *above* the slide level will not appear in the slide
-    show.
+    Non-slide content under these headers will be included
+    on the title slide (for HTML slide shows) or in a
+    subsequent slide with the same title (for beamer).
 
   * A title page is constructed automatically from the document's title
     block, if present.  (In the case of beamer, this can be disabled
@@ -5056,6 +5071,52 @@
 
 Custom styles can be used in the docx and ICML formats.
 
+Output
+------
+
+By default, pandoc's docx and ICML output applies a predefined set of styles
+for blocks such as paragraphs and block quotes, and uses largely default
+formatting (italics, bold) for inlines. This will work for most
+purposes, especially alongside a `reference.docx` file. However, if you
+need to apply your own styles to blocks, or match a preexisting set of
+styles, pandoc allows you to define custom styles for blocks and text
+using `div`s and `span`s, respectively.
+
+If you define a `div` or `span` with the attribute `custom-style`,
+pandoc will apply your specified style to the contained elements. So,
+for example using the `bracketed_spans` syntax,
+
+    [Get out]{custom-style="Emphatically"}, he said.
+
+would produce a docx file with "Get out" styled with character
+style `Emphatically`. Similarly, using the `fenced_divs` syntax,
+
+    Dickinson starts the poem simply:
+
+    ::: {custom-style="Poetry"}
+    | A Bird came down the Walk---
+    | He did not know I saw---
+    :::
+
+would style the two contained lines with the `Poetry` paragraph style.
+
+For docx output, styles will be defined in the output file as inheriting
+from normal text, if the styles are not yet in your reference.docx.
+If they are already defined, pandoc will not alter the definition.
+
+This feature allows for greatest customization in conjunction with
+[pandoc filters]. If you want all paragraphs after block quotes to be
+indented, you can write a filter to apply the styles necessary. If you
+want all italics to be transformed to the `Emphasis` character style
+(perhaps to change their color), you can write a filter which will
+transform all italicized inlines to inlines within an `Emphasis`
+custom-style `span`.
+
+For docx output, you don't need to enable any extensions for
+custom styles to work.
+
+[pandoc filters]: http://pandoc.org/filters.html
+
 Input
 -----
 
@@ -5103,49 +5164,6 @@
 With these custom styles, you can use your input document as a
 reference-doc while creating docx output (see below), and maintain the
 same styles in your input and output files.
-
-Output
-------
-
-By default, pandoc's docx and ICML output applies a predefined set of styles
-for blocks such as paragraphs and block quotes, and uses largely default
-formatting (italics, bold) for inlines. This will work for most
-purposes, especially alongside a `reference.docx` file. However, if you
-need to apply your own styles to blocks, or match a preexisting set of
-styles, pandoc allows you to define custom styles for blocks and text
-using `div`s and `span`s, respectively.
-
-If you define a `div` or `span` with the attribute `custom-style`,
-pandoc will apply your specified style to the contained elements. So,
-for example using the `bracketed_spans` syntax,
-
-    [Get out]{custom-style="Emphatically"}, he said.
-
-would produce a docx file with "Get out" styled with character
-style `Emphatically`. Similarly, using the `fenced_divs` syntax,
-
-    Dickinson starts the poem simply:
-
-    ::: {custom-style="Poetry"}
-    | A Bird came down the Walk---
-    | He did not know I saw---
-    :::
-
-would style the two contained lines with the `Poetry` paragraph style.
-
-For docx output, styles will be defined in the output file as inheriting
-from normal text, if the styles are not yet in your reference.docx.
-If they are already defined, pandoc will not alter the definition.
-
-This feature allows for greatest customization in conjunction with
-[pandoc filters]. If you want all paragraphs after block quotes to be
-indented, you can write a filter to apply the styles necessary. If you
-want all italics to be transformed to the `Emphasis` character style
-(perhaps to change their color), you can write a filter which will
-transform all italicized inlines to inlines within an `Emphasis`
-custom-style `span`.
-
-[pandoc filters]: http://pandoc.org/filters.html
 
 Custom writers
 ==============
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -81,7 +81,8 @@
 
 <div id="output-formats">
 
-  - `asciidoc` ([AsciiDoc](http://www.methods.co.nz/asciidoc/))
+  - `asciidoc` ([AsciiDoc](http://www.methods.co.nz/asciidoc/)) or
+    `asciidoctor` ([AsciiDoctor](https://asciidoctor.org/))
   - `beamer` ([LaTeX beamer](https://ctan.org/pkg/beamer) slide show)
   - `commonmark` ([CommonMark](http://commonmark.org) Markdown)
   - `context` ([ConTeXt](http://www.contextgarden.net/))
diff --git a/benchmark/benchmark-pandoc.hs b/benchmark/benchmark-pandoc.hs
--- a/benchmark/benchmark-pandoc.hs
+++ b/benchmark/benchmark-pandoc.hs
@@ -1,7 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE TupleSections #-}
 {-
-Copyright (C) 2012-2018 John MacFarlane <jgm@berkeley.edu>
+Copyright (C) 2012-2019 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
diff --git a/benchmark/weigh-pandoc.hs b/benchmark/weigh-pandoc.hs
--- a/benchmark/weigh-pandoc.hs
+++ b/benchmark/weigh-pandoc.hs
@@ -1,4 +1,15 @@
 {-# LANGUAGE NoImplicitPrelude #-}
+{- |
+   Module      : Main
+   Copyright   : © 2016-2019 John MacFarlane <jgm@berkeley.edu>
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Benchmarks to determine resource use of readers and writers.
+-}
 import Prelude
 import Weigh
 import Text.Pandoc
diff --git a/changelog b/changelog
--- a/changelog
+++ b/changelog
@@ -1,4 +1,248 @@
-pandoc (2.6) PROVISIONAL
+pandoc (2.7)
+
+  * Use XDG data directory for user data directory (#3582). Instead of
+    `$HOME/.pandoc`, the default user data directory is now
+    `$XDG_DATA_HOME/pandoc`, where `XDG_DATA_HOME` defaults to
+    `$HOME/.local/share` but can be overridden by setting the
+    environment variable. If this directory is missing, then
+    `$HOME/.pandoc` is searched instead, for backwards compatibility.
+    However, we recommend moving local pandoc data files from
+    `$HOME/.pandoc` to `$HOME/.local/share/pandoc`. On Windows the
+    default user data directory remains the same.
+
+  * Slide show formats behavior change:  content under headers
+    less than slide level is no longer ignored, but included in
+    the title slide (for HTML slide shows) or in a slide after
+    the title slide (for beamer).  This change makes possible
+    2D reveal.js slideshows with content in the top slide on
+    each stack (#4317, #5237).
+ 
+  * Add command line option `--ipynb-output=all|none|best` (#5339).
+    Output cells in ipynb notebooks often contain several different
+    versions of an output, with different MIME types, e.g. an HTML
+    table and a plain-text fallback.  Specifying `--ipynb-output=best`
+    (the default) ensures that the best version for the output format
+    is used.  `all` includes all versions, and `none` suppresses them
+    all, leaving output cells empty.
+
+  * `asciidoctor` is now an output format separate from `asciidoc`,
+    to accommodate some minor implementation-specific differences
+    (currently just in the treatment of display math).
+
+  * Add `latexmk` as an option for `--pdf-engine` (#3195).
+    Note that you can use `--pdf-engine-opt=-outdir=bar` to specify
+    a persistent temp directory.
+
+  * Markdown reader:
+
+    + Improve tight/loose list handling (#5285). Previously the
+      algorithm allowed list items with a mix of Para and Plain, which
+      is never wanted.
+    + Add newline when parsing blocks in YAML (#5271). Otherwise last
+      block gets parsed as a Plain rather than a Para. This is a
+      regression in pandoc 2.x. This patch restores pandoc 1.19
+      behavior.
+    + Make `yamlToMeta` respect extensions (#5272, Mauro Bieg).
+      This adds a `ReaderOptions` parameter to `yamlToMeta` [API change].
+    + Fix bug parsing fenced code blocks (#5304). Previously parsing
+      would break if the code block contained a string of backticks of
+      sufficient length followed by something other than end of line.
+
+  * LaTeX reader: don't let `\egroup` match `{`. `braced` now actually
+    requires nested braces. Otherwise some legitimate command and
+    environment definitions can break.
+
+  * Docx reader (Jesse Rosenthal):
+
+    + Rename `getDocumentPath` as `getDocumentXmlPath`.
+    + Use field notation for setting `ReaderEnv`.
+    + Figure out `document.xml` path once at the beginning of parsing, and
+      add it to the environment, so we can avoid repeated lookups.
+    + Dynamically determine main document xml path (#5277).
+      The desktop Word program places the main document file in
+      `word/document.xml`, but the online word places it in
+      `word/document2.xml`. This file path is actually stated in the root
+      `_rels/.rels` file, in the `Relationship` element with an
+      `http://../officedocument` type.
+    + Fix paths in archive to prevent Windows failure (#5277).
+      Some paths in archives are absolute (have an opening slash) which, for
+      reasons unknown, produces a failure in the test suite on MS
+      Windows. This fixes that by removing the leading slash if it exists.
+    + Add comments to aid code readability.
+    + Trim space inside the last inline (#5273).
+    + Unwrap sdt elements in footnotes and comments (#5302).
+
+  * Muse reader (Alexander Krotov):
+
+    + Test that block level markup does not break `<verbatim>`.
+    + Add secondary note support.
+
+  * ipynb reader: handle images referring to attachments. Previously
+    we didn't strip off the attachment: prefix, so even though the
+    attachment was available in the mediabag, pandoc couldn't find it.
+
+  * JATS reader:
+
+    + Fix parsing of figures (#5321). This ensures that a figure
+      containing a single image is parsed as a pandoc "implicit
+      figure" (i.e., a Para with a single Image whose title attribute
+      begins with `fig:`). More complex figures will still be parsed
+      as divs.
+    + Support `fig-group` block element (#5317).
+    + Handle citations with multiple references (#5310). The `rid`
+      attribute can have a space-separated list of ids.
+
+  * AsciiDoc Writer: Add `writeAsciiDoctor` [API change, Tarik Graba].
+    Handle display math appropriately for Asciidoctor.
+
+  * JATS writer: wrap figure caption in `<p>` to fix validation (#5290,
+    Mauro Bieg).
+
+  * HTML writer:
+
+    + Implement WAI-ARIA roles for (end)notes, citations, and
+      bibliography (#4213). Note that doc-biblioref is only used when
+      link-citations produces links, since it belongs on links.
+    + Include content (including speaker notes) in title slides
+      (#4317, #5237).
+
+  * ipynb writer:
+
+    + Ensure final newline.
+    + Only include metadata under `jupyter` field.
+    + Don't create attachments for images with absolute URIs,
+      including data: URIs (#5303).
+    + Keep plain text fallbacks in output even if a richer format is
+      included (#5293). We don't know what output format will be needed.
+      See the `--ipynb-output` command line option for a way to control
+      what formats are included in the output.
+
+  * Markdown writer: use `markdown="1"` when appropriate for Divs:
+    when `native_divs` and `markdown_in_html_blocks` are disabled
+    but `raw_html` and `markdown_attribute` are enabled.
+
+  * LaTeX writer:
+
+    + Use right fold for `escapeString`.  This is more elegant than
+      the explicit recursive code we were using.
+    + Avoid `{}` after control sequences when escaping.
+      `\ldots{}.` doesn't behave as well as `\ldots.` with the latex
+      ellipsis package.  This patch causes pandoc to avoid emitting
+      the `{}` when it is not necessary.  Now `\ldots` and other
+      control sequences used in escaping will be followed by either
+      a `{}`, a space, or nothing, depending on context.
+    + For beamer, include contents under headers superordinate to
+      slidelevel (#4317). Currently we keep the fancy title slide, and
+      add a new slide with the same title and whatever content was
+      under the header.
+
+  * Powerpoint writer (Jesse Rosenthal): support underlines.
+    Use span with single class "underline" as in docx writer.
+
+  * Muse writer: escape secondary notes (Alexander Krotov).
+
+  * FB2 writer: add section identifiers support (#5229, John KetzerX).
+
+  * Make `--fail-if-warnings` work for PDF output (#5343).
+
+  * Lua filters (Albert Krewinkel):
+
+    + Load module `pandoc` before calling `init.lua` (#5287). The file
+      `init.lua` in pandoc's data directory is run as part of pandoc's
+      Lua initialization process. Previously, the `pandoc` module was
+      loaded in `init.lua`, and the structure for marshaling was
+      set up after. This allowed simple patching of element
+      marshaling, but made using `init.lua` more difficult. Now, all
+      required modules are now loaded before calling `init.lua`. The
+      file can be used entirely for user customization. Patching
+      marshaling functions, while discouraged, is still possible via
+      the `debug` module.
+    + All Lua modules bundled with pandoc, i.e., `pandoc.List`,
+      `pandoc.mediabag`, `pandoc.utils`, and `text` are re-exported from the
+      `pandoc` module. They are assigned to the fields `List`, `mediabag`,
+      `utils`, and `text`, respectively.
+
+  * Text.Pandoc.Lua (Albert Krewinkel):
+  
+    + Split `StackInstances` into smaller Marshaling modules.
+    + Get `CommonState` from Lua global. This allows more control over
+      the common state from within Lua scripts.
+
+  * LaTeX template:
+
+    + Support the `subject` metadata variable (#5289, Pascal Wagler).
+    + Add \frontmatter, \mainmatter, \backmatter for book classes (#5306).
+
+  * epub3 template: Add titlepage class to section (#5269).
+
+  * HTML5 template: Add ARIA role `doc-toc` for table of contents (#4213).
+
+  * Make --metadata-file use pandoc-markdown (#5279, #5272, Mauro Bieg).
+
+  * Text.Pandoc.Shared:
+
+    + Remove `withTempDir` [API change].
+    + Add new exported function `defaultUserDataDirs` [API change].
+    + Add `filterIpynbOutput` [API change].
+    + `compactify`: Avoid lists with a mix of Plain and Para elements
+      (#5285).
+
+  * Text.Pandoc.Translations: reorder alphabetically and remove `Author`
+    (#5334, Mauro Bieg).
+
+  * Text.Pandoc.Extensions:
+
+    + More carefully groom ipynb default extensions.
+    + Add `all_symbols_escapable` to `githubMarkdownExtensions`.
+
+  * Text.Pandoc.PDF:
+
+    + Use system temp directory when possible (#1192). Previously we
+      created temp dirs in the working directory, partly (a) because
+      there were problems using the system temp directory on Windows,
+      when their pathnames included tildes, and partly (b) because
+      programs like `epstopdf.pl` would not be allowed to write to
+      directories outside the working directory in restricted mode. We
+      now (a) use the system temp dir except when the path includes
+      tildes, and (b) set `TEXMFOUTPUT` when creating the PDF, so that
+      subsidiary programs can use the system temp directory. This
+      addresses problems that occurred when pandoc was used in a
+      synced directory (such as Dropbox).
+    + Change types of subsidiary functions to PandocIO, to allow
+      warnings to be threaded through (#5343).
+
+  * Text.Pandoc.MIME: add WebP (#5267, Mauro Bieg).
+
+  * Tests: avoid calling `findPandoc` multiple times.
+
+  * Old tests: remove need for temp files by using `pipeProcess`.
+
+  * Added simple ipynb reader/writer tests (#5274).
+
+  * Rearrange `--help` output in a more rational way, with common
+    options at the beginning and options grouped by function (#5336).
+
+  * trypandoc: Add JATS and other missing formats (Arfon Smith, #5291).
+
+  * Add missing copyright notices and remove license boilerplate (#4592,
+    Albert Krewinkel).
+
+  * Use latest basement/foundation on 32bit windows.
+
+  * Use latest skylighting (#5328). Custom syntax definitions no
+    longer try to load `language.dtd`.
+
+  * Require texmath 0.11.2.1
+
+  * Use latest pandoc-citeproc (0.16.1.1).
+
+  * MANUAL.txt:
+
+    + Clarify variable substitution indentation in templates (#5338,
+      Agustín Martín Barbero).
+    + Reorder custom-styles section (#5324, Mauro Bieg).
+
+pandoc (2.6)
 
   * Support ipynb (Jupyter notebook) as input and output format.
 
diff --git a/data/bash_completion.tpl b/data/bash_completion.tpl
--- a/data/bash_completion.tpl
+++ b/data/bash_completion.tpl
@@ -29,8 +29,12 @@
              COMPREPLY=( $(compgen -W "references javascript none" -- ${cur}) )
              return 0
              ;;
+         --ipynb-output)
+             COMPREPLY=( $(compgen -W "all none best" -- ${cur}) )
+             return 0
+             ;;
          --pdf-engine)
-             COMPREPLY=( $(compgen -W "pdflatex lualatex xelatex wkhtmltopdf weasyprint prince context pdfroff" -- ${cur}) )
+             COMPREPLY=( $(compgen -W "pdflatex lualatex xelatex latexmk wkhtmltopdf weasyprint prince context pdfroff" -- ${cur}) )
              return 0
              ;;
          --print-default-data-file)
diff --git a/data/init.lua b/data/init.lua
--- a/data/init.lua
+++ b/data/init.lua
@@ -1,7 +1,3 @@
 -- This Lua script is run every time the Lua interpreter is started when running
 -- a Lua filter. It can be customized to load additional modules or to alter the
 -- default modules.
-
-pandoc = require 'pandoc'
-pandoc.mediabag = require 'pandoc.mediabag'
-pandoc.utils = require 'pandoc.utils'
diff --git a/data/pandoc.lua b/data/pandoc.lua
--- a/data/pandoc.lua
+++ b/data/pandoc.lua
@@ -1,7 +1,7 @@
 --[[
 pandoc.lua
 
-Copyright © 2017–2018 Albert Krewinkel
+Copyright © 2017–2019 Albert Krewinkel
 
 Permission to use, copy, modify, and/or distribute this software for any purpose
 with or without fee is hereby granted, provided that the above copyright notice
@@ -20,12 +20,20 @@
 -- Lua functions for pandoc scripts.
 --
 -- @author Albert Krewinkel
--- @copyright © 2017–2018 Albert Krewinkel
+-- @copyright © 2017–2019 Albert Krewinkel
 -- @license MIT
 local M = {}
 
-local List = require 'pandoc.List'
-local utils = require 'pandoc.utils'
+-- Re-export bundled modules
+M.List = require 'pandoc.List'
+M.mediabag = require 'pandoc.mediabag'
+M.utils = require 'pandoc.utils'
+M.text = require 'text'
+
+-- Local names for modules which this module depends on.
+local List = M.List
+local utils = M.utils
+
 
 ------------------------------------------------------------------------
 -- Accessor objects
diff --git a/data/templates/default.asciidoctor b/data/templates/default.asciidoctor
new file mode 100644
--- /dev/null
+++ b/data/templates/default.asciidoctor
@@ -0,0 +1,41 @@
+$if(titleblock)$
+= $title$
+$if(author)$
+$for(author)$$author$$sep$; $endfor$
+$endif$
+$if(date)$
+$date$
+$endif$
+$if(keywords)$
+:keywords: $for(keywords)$$keywords$$sep$, $endfor$
+$endif$
+$if(lang)$
+:lang: $lang$
+$endif$
+$if(toc)$
+:toc:
+$endif$
+$if(math)$
+:stem: latexmath
+$endif$
+
+$endif$
+$if(abstract)$
+[abstract]
+== Abstract
+$abstract$
+
+$endif$
+$for(header-includes)$
+$header-includes$
+
+$endfor$
+$for(include-before)$
+$include-before$
+
+$endfor$
+$body$
+$for(include-after)$
+
+$include-after$
+$endfor$
diff --git a/data/templates/default.epub3 b/data/templates/default.epub3
--- a/data/templates/default.epub3
+++ b/data/templates/default.epub3
@@ -28,7 +28,7 @@
 </head>
 <body$if(coverpage)$ id="cover"$endif$$if(body-type)$ epub:type="$body-type$"$endif$>
 $if(titlepage)$
-<section epub:type="titlepage">
+<section epub:type="titlepage" class="titlepage">
 $for(title)$
 $if(title.type)$
   <h1 class="$title.type$">$title.text$</h1>
diff --git a/data/templates/default.html5 b/data/templates/default.html5
--- a/data/templates/default.html5
+++ b/data/templates/default.html5
@@ -60,7 +60,7 @@
 </header>
 $endif$
 $if(toc)$
-<nav id="$idprefix$TOC">
+<nav id="$idprefix$TOC" role="doc-toc">
 $table-of-contents$
 </nav>
 $endif$
diff --git a/data/templates/default.latex b/data/templates/default.latex
--- a/data/templates/default.latex
+++ b/data/templates/default.latex
@@ -205,6 +205,9 @@
 $if(author-meta)$
   pdfauthor={$author-meta$},
 $endif$
+$if(subject)$
+  pdfsubject={$subject$},
+$endif$
 $if(keywords)$
   pdfkeywords={$for(keywords)$$keywords$$sep$, $endfor$},
 $endif$
@@ -381,6 +384,9 @@
 
 \begin{document}
 $if(title)$
+$if(book-class)$
+\frontmatter
+$endif$
 $if(beamer)$
 \frame{\titlepage}
 $else$
@@ -424,8 +430,14 @@
 $if(lof)$
 \listoffigures
 $endif$
+$if(book-class)$
+\mainmatter
+$endif$
 $body$
 
+$if(book-class)$
+\backmatter
+$endif$
 $if(natbib)$
 $if(bibliography)$
 $if(biblio-title)$
diff --git a/data/translations/de.yaml b/data/translations/de.yaml
--- a/data/translations/de.yaml
+++ b/data/translations/de.yaml
@@ -8,6 +8,7 @@
 Figure: Abbildung
 Glossary: Glossar
 Index: Index
+Listing: Auflistung
 ListOfFigures: Abbildungsverzeichnis
 ListOfTables: Tabellenverzeichnis
 Page: Seite
diff --git a/data/translations/en.yaml b/data/translations/en.yaml
--- a/data/translations/en.yaml
+++ b/data/translations/en.yaml
@@ -8,6 +8,7 @@
 Figure: Figure
 Glossary: Glossary
 Index: Index
+Listing: Listing
 ListOfFigures: ListOfFigures
 ListOfTables: ListOfTables
 Page: page
@@ -19,4 +20,3 @@
 SeeAlso: see also
 Table: Table
 To: To
-Listing: Listing
diff --git a/data/translations/ru.yaml b/data/translations/ru.yaml
--- a/data/translations/ru.yaml
+++ b/data/translations/ru.yaml
@@ -1,6 +1,5 @@
 Abstract: Аннотация
 Appendix: Приложение
-Author: Именной указатель
 Bibliography: Литература
 Cc: исх.
 Chapter: Глава
diff --git a/data/translations/uk.yaml b/data/translations/uk.yaml
--- a/data/translations/uk.yaml
+++ b/data/translations/uk.yaml
@@ -1,6 +1,5 @@
 Abstract: Анотація
 Appendix: Додаток
-Author: Іменний покажчик}% babel has "Їменний покажчик"
 Bibliography: Бібліоґрафія
 Cc: копія
 Chapter: Розділ
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 "January 30, 2019" "pandoc 2.6"
+.TH PANDOC 1 "March 2, 2019" "pandoc 2.7"
 .SH NAME
 pandoc - general markup converter
 .SH SYNOPSIS
@@ -300,7 +300,7 @@
 \f[I]FORMAT\f[R] can be:
 .RS
 .IP \[bu] 2
-\f[C]asciidoc\f[R] (AsciiDoc)
+\f[C]asciidoc\f[R] (AsciiDoc) or \f[C]asciidoctor\f[R] (AsciiDoctor)
 .IP \[bu] 2
 \f[C]beamer\f[R] (LaTeX beamer slide show)
 .IP \[bu] 2
@@ -417,38 +417,20 @@
 Specify the user data directory to search for pandoc data files.
 If this option is not specified, the default user data directory will be
 used.
-This is, in UNIX:
-.RS
-.IP
-.nf
-\f[C]
-$HOME/.pandoc
-\f[R]
-.fi
-.PP
-in Windows XP:
-.IP
-.nf
-\f[C]
-C:\[rs]Documents And Settings\[rs]USERNAME\[rs]Application Data\[rs]pandoc
-\f[R]
-.fi
-.PP
-and in Windows Vista or later:
-.IP
-.nf
-\f[C]
-C:\[rs]Users\[rs]USERNAME\[rs]AppData\[rs]Roaming\[rs]pandoc
-\f[R]
-.fi
-.PP
+On *nix and macOS systems this will be the \f[C]pandoc\f[R] subdirectory
+of the XDG data directory (by default, \f[C]$HOME/.local/share\f[R],
+overridable by setting the \f[C]XDG_DATA_HOME\f[R] environment
+variable).
+If that directory does not exist, \f[C]$HOME/.pandoc\f[R] will be used
+(for backwards compatibility).
+In Windows the default user data directory is
+\f[C]C:\[rs]Users\[rs]USERNAME\[rs]AppData\[rs]Roaming\[rs]pandoc\f[R].
 You can find the default user data directory on your system by looking
 at the output of \f[C]pandoc --version\f[R].
 A \f[C]reference.odt\f[R], \f[C]reference.docx\f[R], \f[C]epub.css\f[R],
 \f[C]templates\f[R], \f[C]slidy\f[R], \f[C]slideous\f[R], or
 \f[C]s5\f[R] directory placed in this directory will override
 pandoc\[aq]s normal defaults.
-.RE
 .TP
 .B \f[C]--bash-completion\f[R]
 Generate a bash completion script.
@@ -1275,8 +1257,21 @@
 The default is \f[C]EPUB\f[R].
 To put the EPUB contents in the top level, use an empty string.
 .TP
-.B \f[C]--pdf-engine=pdflatex\f[R]|\f[C]lualatex\f[R]|\f[C]xelatex\f[R]|\f[C]wkhtmltopdf\f[R]|\f[C]weasyprint\f[R]|\f[C]prince\f[R]|\f[C]context\f[R]|\f[C]pdfroff\f[R]
+.B \f[C]--ipynb-output=all|none|best\f[R]
+Determines how ipynb output cells are treated.
+\f[C]all\f[R] means that all of the data formats included in the
+original are preserved.
+\f[C]none\f[R] means that the contents of data cells are omitted.
+\f[C]best\f[R] causes pandoc to try to pick the richest data block in
+each output cell that is compatible with the output format.
+The default is \f[C]best\f[R].
+.TP
+.B \f[C]--pdf-engine=\f[R]\f[I]PROGRAM\f[R]
 Use the specified engine when producing PDF output.
+Valid values are \f[C]pdflatex\f[R], \f[C]lualatex\f[R],
+\f[C]xelatex\f[R], \f[C]latexmk\f[R], \f[C]wkhtmltopdf\f[R],
+\f[C]weasyprint\f[R], \f[C]prince\f[R], \f[C]context\f[R], and
+\f[C]pdfroff\f[R].
 The default is \f[C]pdflatex\f[R].
 If the engine is not in your PATH, the full path of the engine may be
 specified here.
@@ -1284,8 +1279,9 @@
 .B \f[C]--pdf-engine-opt=\f[R]\f[I]STRING\f[R]
 Use the given string as a command-line argument to the
 \f[C]pdf-engine\f[R].
-If used multiple times, the arguments are provided with spaces between
-them.
+For example, to use a persistent directory \f[C]foo\f[R] for
+\f[C]latexmk\f[R]\[aq]s auxiliary files, use
+\f[C]--pdf-engine-opt=-outdir=foo\f[R].
 Note that no check for duplicate options is done.
 .SS Citation rendering
 .TP
@@ -1500,7 +1496,7 @@
 AsciiDoc metadata; repeat as for \f[C]author\f[R], above
 .TP
 .B \f[C]subject\f[R]
-document subject, included in ODT, docx and pptx metadata
+document subject, included in ODT, PDF, docx and pptx metadata
 .TP
 .B \f[C]description\f[R]
 document description, included in ODT, docx and pptx metadata.
@@ -2073,6 +2069,9 @@
 \f[R]
 .fi
 .PP
+The value of a variable will be indented to the same level as the
+variable.
+.PP
 If you use custom templates, you may need to revise them as pandoc
 changes.
 We recommend tracking the changes in the default templates, and
@@ -2412,9 +2411,9 @@
 \f[C]docx\f[R], \f[C]odt\f[R], \f[C]opendocument\f[R], \f[C]html\f[R]
 .SS Extension: \f[C]styles\f[R]
 .PP
-Read all docx styles as divs (for paragraph styles) and spans (for
-character styles) regardless of whether pandoc understands the meaning
-of these styles.
+When converting from docx, read all docx styles as divs (for paragraph
+styles) and spans (for character styles) regardless of whether pandoc
+understands the meaning of these styles.
 This can be used with docx custom styles.
 Disabled by default.
 .TP
@@ -4053,7 +4052,11 @@
 It will be rendered using an interpreted text role \f[C]:math:\f[R].
 .TP
 .B AsciiDoc
-It will be rendered as \f[C]latexmath:[...]\f[R].
+For AsciiDoc output format (\f[C]-t asciidoc\f[R]) it will appear
+verbatim surrounded by \f[C]latexmath:[$...$]\f[R] (for inline math) or
+\f[C][latexmath]++++\[rs][...\[rs]]+++\f[R] (for display math).
+For AsciiDoctor output format (\f[C]-t asciidoctor\f[R]) the LaTex
+delimiters (\f[C]$..$\f[R] and \f[C]\[rs][..\[rs]]\f[R]) are omitted.
 .TP
 .B Texinfo
 It will be rendered inside a \f[C]\[at]math\f[R] command.
@@ -5313,9 +5316,9 @@
 Headers \f[I]above\f[R] the slide level in the hierarchy create
 \[dq]title slides,\[dq] which just contain the section title and help to
 break the slide show into sections.
-.IP \[bu] 2
-Content \f[I]above\f[R] the slide level will not appear in the slide
-show.
+Non-slide content under these headers will be included on the title
+slide (for HTML slide shows) or in a subsequent slide with the same
+title (for beamer).
 .IP \[bu] 2
 A title page is constructed automatically from the document\[aq]s title
 block, if present.
@@ -5980,6 +5983,61 @@
 .SH CUSTOM STYLES
 .PP
 Custom styles can be used in the docx and ICML formats.
+.SS Output
+.PP
+By default, pandoc\[aq]s docx and ICML output applies a predefined set
+of styles for blocks such as paragraphs and block quotes, and uses
+largely default formatting (italics, bold) for inlines.
+This will work for most purposes, especially alongside a
+\f[C]reference.docx\f[R] file.
+However, if you need to apply your own styles to blocks, or match a
+preexisting set of styles, pandoc allows you to define custom styles for
+blocks and text using \f[C]div\f[R]s and \f[C]span\f[R]s, respectively.
+.PP
+If you define a \f[C]div\f[R] or \f[C]span\f[R] with the attribute
+\f[C]custom-style\f[R], pandoc will apply your specified style to the
+contained elements.
+So, for example using the \f[C]bracketed_spans\f[R] syntax,
+.IP
+.nf
+\f[C]
+[Get out]{custom-style=\[dq]Emphatically\[dq]}, he said.
+\f[R]
+.fi
+.PP
+would produce a docx file with \[dq]Get out\[dq] styled with character
+style \f[C]Emphatically\f[R].
+Similarly, using the \f[C]fenced_divs\f[R] syntax,
+.IP
+.nf
+\f[C]
+Dickinson starts the poem simply:
+
+::: {custom-style=\[dq]Poetry\[dq]}
+| A Bird came down the Walk---
+| He did not know I saw---
+:::
+\f[R]
+.fi
+.PP
+would style the two contained lines with the \f[C]Poetry\f[R] paragraph
+style.
+.PP
+For docx output, styles will be defined in the output file as inheriting
+from normal text, if the styles are not yet in your reference.docx.
+If they are already defined, pandoc will not alter the definition.
+.PP
+This feature allows for greatest customization in conjunction with
+pandoc filters.
+If you want all paragraphs after block quotes to be indented, you can
+write a filter to apply the styles necessary.
+If you want all italics to be transformed to the \f[C]Emphasis\f[R]
+character style (perhaps to change their color), you can write a filter
+which will transform all italicized inlines to inlines within an
+\f[C]Emphasis\f[R] custom-style \f[C]span\f[R].
+.PP
+For docx output, you don\[aq]t need to enable any extensions for custom
+styles to work.
 .SS Input
 .PP
 The docx reader, by default, only reads those styles that it can convert
@@ -6034,58 +6092,6 @@
 With these custom styles, you can use your input document as a
 reference-doc while creating docx output (see below), and maintain the
 same styles in your input and output files.
-.SS Output
-.PP
-By default, pandoc\[aq]s docx and ICML output applies a predefined set
-of styles for blocks such as paragraphs and block quotes, and uses
-largely default formatting (italics, bold) for inlines.
-This will work for most purposes, especially alongside a
-\f[C]reference.docx\f[R] file.
-However, if you need to apply your own styles to blocks, or match a
-preexisting set of styles, pandoc allows you to define custom styles for
-blocks and text using \f[C]div\f[R]s and \f[C]span\f[R]s, respectively.
-.PP
-If you define a \f[C]div\f[R] or \f[C]span\f[R] with the attribute
-\f[C]custom-style\f[R], pandoc will apply your specified style to the
-contained elements.
-So, for example using the \f[C]bracketed_spans\f[R] syntax,
-.IP
-.nf
-\f[C]
-[Get out]{custom-style=\[dq]Emphatically\[dq]}, he said.
-\f[R]
-.fi
-.PP
-would produce a docx file with \[dq]Get out\[dq] styled with character
-style \f[C]Emphatically\f[R].
-Similarly, using the \f[C]fenced_divs\f[R] syntax,
-.IP
-.nf
-\f[C]
-Dickinson starts the poem simply:
-
-::: {custom-style=\[dq]Poetry\[dq]}
-| A Bird came down the Walk---
-| He did not know I saw---
-:::
-\f[R]
-.fi
-.PP
-would style the two contained lines with the \f[C]Poetry\f[R] paragraph
-style.
-.PP
-For docx output, styles will be defined in the output file as inheriting
-from normal text, if the styles are not yet in your reference.docx.
-If they are already defined, pandoc will not alter the definition.
-.PP
-This feature allows for greatest customization in conjunction with
-pandoc filters.
-If you want all paragraphs after block quotes to be indented, you can
-write a filter to apply the styles necessary.
-If you want all italics to be transformed to the \f[C]Emphasis\f[R]
-character style (perhaps to change their color), you can write a filter
-which will transform all italicized inlines to inlines within an
-\f[C]Emphasis\f[R] custom-style \f[C]span\f[R].
 .SH CUSTOM WRITERS
 .PP
 Pandoc can be extended with custom writers written in lua.
diff --git a/pandoc.cabal b/pandoc.cabal
--- a/pandoc.cabal
+++ b/pandoc.cabal
@@ -1,5 +1,5 @@
 name:            pandoc
-version:         2.6
+version:         2.7
 cabal-version:   2.0
 build-type:      Simple
 license:         GPL-2
@@ -70,6 +70,7 @@
                  data/templates/default.revealjs
                  data/templates/default.dzslides
                  data/templates/default.asciidoc
+                 data/templates/default.asciidoctor
                  data/templates/default.haddock
                  data/templates/default.textile
                  data/templates/default.org
@@ -321,6 +322,9 @@
                  test/epub/*.native
                  test/pptx/*.pptx
                  test/pptx/*.native
+                 test/ipynb/*.in.native
+                 test/ipynb/*.out.native
+                 test/ipynb/*.ipynb
                  test/txt2tags.t2t
                  test/twiki-reader.twiki
                  test/tikiwiki-reader.tikiwiki
@@ -359,14 +363,14 @@
                  exceptions >= 0.8 && < 0.11,
                  filepath >= 1.1 && < 1.5,
                  process >= 1.2.3 && < 1.7,
-                 directory >= 1 && < 1.4,
+                 directory >= 1.2.3 && < 1.4,
                  bytestring >= 0.9 && < 0.11,
                  text >= 1.1.1.0 && < 1.3,
                  time >= 1.5 && < 1.10,
                  safe >= 0.3 && < 0.4,
                  zip-archive >= 0.2.3.4 && < 0.5,
                  HTTP >= 4000.0.5 && < 4000.4,
-                 texmath >= 0.11 && < 0.12,
+                 texmath >= 0.11.2.1 && < 0.12,
                  xml >= 1.3.12 && < 1.4,
                  split >= 0.2 && < 0.3,
                  random >= 1 && < 1.2,
@@ -376,7 +380,7 @@
                  tagsoup >= 0.14.6 && < 0.15,
                  base64-bytestring >= 0.1 && < 1.1,
                  zlib >= 0.5 && < 0.7,
-                 skylighting >= 0.7.5 && < 0.8,
+                 skylighting >= 0.7.7 && < 0.8,
                  data-default >= 0.4 && < 0.8,
                  temporary >= 1.1 && < 1.4,
                  blaze-html >= 0.9 && < 0.10,
@@ -404,9 +408,13 @@
   if impl(ghc < 8.0)
     build-depends: semigroups == 0.18.*,
                    -- basement 0.0.8 and foundation 0.0.21, transitive
-                   -- dependencies, drop support for ghc 7.10:
+                   -- dependencies, drop support for ghc 7.10.
                    basement < 0.0.8,
                    foundation < 0.0.21
+  if impl(ghc >= 8.0) && os(windows) && arch(i386)
+     build-depends: basement >= 0.0.10,
+                    foundation >= 0.0.23
+                    -- basement 0.0.9 won't build on 32-bit windows.
   if impl(ghc < 8.4)
      hs-source-dirs: prelude
      other-modules:  Prelude
@@ -567,11 +575,15 @@
                    Text.Pandoc.Lua.Filter,
                    Text.Pandoc.Lua.Global,
                    Text.Pandoc.Lua.Init,
+                   Text.Pandoc.Lua.Marshaling,
+                   Text.Pandoc.Lua.Marshaling.AST,
+                   Text.Pandoc.Lua.Marshaling.AnyValue,
+                   Text.Pandoc.Lua.Marshaling.CommonState,
+                   Text.Pandoc.Lua.Marshaling.ReaderOptions,
                    Text.Pandoc.Lua.Module.MediaBag,
                    Text.Pandoc.Lua.Module.Pandoc,
                    Text.Pandoc.Lua.Module.Utils,
                    Text.Pandoc.Lua.Packages,
-                   Text.Pandoc.Lua.StackInstances,
                    Text.Pandoc.Lua.Util,
                    Text.Pandoc.CSS,
                    Text.Pandoc.CSV,
@@ -649,7 +661,7 @@
                   base64-bytestring >= 0.1 && < 1.1,
                   text >= 1.1.1.0 && < 1.3,
                   time >= 1.5 && < 1.10,
-                  directory >= 1 && < 1.4,
+                  directory >= 1.2.3 && < 1.4,
                   filepath >= 1.1 && < 1.5,
                   hslua >= 1.0 && < 1.1,
                   process >= 1.2.3 && < 1.7,
diff --git a/pandoc.hs b/pandoc.hs
--- a/pandoc.hs
+++ b/pandoc.hs
@@ -1,22 +1,4 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-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      : Main
    Copyright   : Copyright (C) 2006-2018 John MacFarlane
diff --git a/src/Text/Pandoc.hs b/src/Text/Pandoc.hs
--- a/src/Text/Pandoc.hs
+++ b/src/Text/Pandoc.hs
@@ -1,27 +1,9 @@
 {-# LANGUAGE FlexibleInstances   #-}
 {-# LANGUAGE GADTs               #-}
 {-# LANGUAGE ScopedTypeVariables #-}
-{-
-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
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
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
@@ -1,27 +1,9 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE CPP                 #-}
 {-# LANGUAGE ScopedTypeVariables #-}
-{-
-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.App
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley@edu>
@@ -56,7 +38,7 @@
 import qualified Data.Text.Encoding.Error as TE
 import qualified Data.Text.Encoding.Error as TSE
 import Network.URI (URI (..), parseURI)
-import System.Directory (getAppUserDataDirectory)
+import System.Directory (doesDirectoryExist)
 import System.Exit (exitSuccess)
 import System.FilePath
 import System.IO (nativeNewline, stdout)
@@ -73,7 +55,8 @@
 import Text.Pandoc.Readers.Markdown (yamlToMeta)
 import Text.Pandoc.SelfContained (makeDataURI, makeSelfContained)
 import Text.Pandoc.Shared (eastAsianLineBreakFilter, stripEmptyParagraphs,
-         headerShift, isURI, tabFilter, uriPathToPath)
+         headerShift, isURI, tabFilter, uriPathToPath, filterIpynbOutput,
+         defaultUserDataDirs)
 import qualified Text.Pandoc.UTF8 as UTF8
 #ifndef _WINDOWS
 import System.Posix.IO (stdOutput)
@@ -107,10 +90,15 @@
                         | otherwise  -> xs
 
   datadir <- case optDataDir opts of
-                  Nothing   -> E.catch
-                                 (Just <$> getAppUserDataDirectory "pandoc")
-                                 (\e -> let _ = (e :: E.SomeException)
-                                        in  return Nothing)
+                  Nothing   -> do
+                    ds <- defaultUserDataDirs
+                    let selectUserDataDir [] = return Nothing
+                        selectUserDataDir (dir:dirs) = do
+                              exists <- doesDirectoryExist dir
+                              if exists
+                                 then return (Just dir)
+                                 else selectUserDataDir dirs
+                    selectUserDataDir ds
                   Just _    -> return $ optDataDir opts
 
   -- assign reader and writer based on options and filenames
@@ -211,10 +199,6 @@
                                          ("application/xml", jatsCSL)
                      return $ ("csl", jatsEncoded) : optMetadata opts
                    else return $ optMetadata opts
-    metadataFromFile <-
-      case optMetadataFile opts of
-        Nothing   -> return mempty
-        Just file -> readFileLazy file >>= yamlToMeta
 
     case lookup "lang" (optMetadata opts) of
            Just l  -> case parseBCP47 l of
@@ -235,6 +219,11 @@
           , readerStripComments = optStripComments opts
           }
 
+    metadataFromFile <-
+      case optMetadataFile opts of
+        Nothing   -> return mempty
+        Just file -> readFileLazy file >>= yamlToMeta readerOpts
+
     let transforms = (case optBaseHeaderLevel opts of
                           x | x > 1     -> (headerShift (x - 1) :)
                             | otherwise -> id) .
@@ -247,8 +236,20 @@
                               (writerExtensions writerOptions) &&
                               writerWrapText writerOptions == WrapPreserve)
                          then (eastAsianLineBreakFilter :)
-                         else id) $
-                     []
+                         else id) .
+                     (case optIpynbOutput opts of
+                       "all"    -> id
+                       "none"   -> (filterIpynbOutput Nothing :)
+                       "best"   -> (filterIpynbOutput (Just $
+                                     if htmlFormat writerName
+                                        then Format "html"
+                                        else
+                                          case writerName of
+                                            "latex"  -> Format "latex"
+                                            "beamer" -> Format "latex"
+                                            _        -> Format writerName) :)
+                       _  -> id)  -- should not happen
+                     $ []
 
     let sourceToDoc :: [FilePath] -> PandocIO Pandoc
         sourceToDoc sources' =
@@ -293,21 +294,22 @@
                                      TL.unpack (TE.decodeUtf8With TE.lenientDecode err')
 
         Nothing -> do
-                let htmlFormat = format `elem`
-                      ["html","html4","html5","s5","slidy",
-                       "slideous","dzslides","revealjs"]
-                    addNl = if standalone
+                let addNl = if standalone
                                then id
                                else (<> T.singleton '\n')
                 output <- addNl <$> f writerOptions doc
                 writerFn eol outputFile =<<
-                  if optSelfContained opts && htmlFormat
+                  if optSelfContained opts && htmlFormat writerName
                      -- TODO not maximally efficient; change type
                      -- of makeSelfContained so it works w/ Text
                      then T.pack <$> makeSelfContained (T.unpack output)
                      else return output
 
 type Transform = Pandoc -> Pandoc
+
+htmlFormat :: String -> Bool
+htmlFormat = (`elem` ["html","html4","html5","s5","slidy",
+                      "slideous","dzslides","revealjs"])
 
 isTextFormat :: String -> Bool
 isTextFormat s = s `notElem` ["odt","docx","epub2","epub3","epub","pptx"]
diff --git a/src/Text/Pandoc/App/CommandLineOptions.hs b/src/Text/Pandoc/App/CommandLineOptions.hs
--- a/src/Text/Pandoc/App/CommandLineOptions.hs
+++ b/src/Text/Pandoc/App/CommandLineOptions.hs
@@ -5,27 +5,9 @@
 #ifdef DERIVE_JSON_VIA_TH
 {-# LANGUAGE TemplateHaskell     #-}
 #endif
-{-
-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.App.CommandLineOptions
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley@edu>
@@ -64,15 +46,14 @@
 import Text.Pandoc.Filter (Filter (..))
 import Text.Pandoc.Highlighting (highlightingStyles)
 import Text.Pandoc.Writers.Math (defaultMathJaxURL, defaultKaTeXURL)
-import Text.Pandoc.Shared (ordNub, safeRead)
+import Text.Pandoc.Shared (ordNub, safeRead, defaultUserDataDirs)
 import Text.Printf
 
 #ifdef EMBED_DATA_FILES
 import Text.Pandoc.Data (dataFiles)
-import System.Directory (getAppUserDataDirectory)
 #else
 import Paths_pandoc (getDataDir)
-import System.Directory (getAppUserDataDirectory, getDirectoryContents)
+import System.Directory (getDirectoryContents)
 #endif
 
 import qualified Control.Exception as E
@@ -104,7 +85,7 @@
   return (opts{ optInputFiles = map normalizePath args })
 
 latexEngines :: [String]
-latexEngines  = ["pdflatex", "lualatex", "xelatex"]
+latexEngines  = ["pdflatex", "lualatex", "xelatex", "latexmk"]
 
 htmlEngines :: [String]
 htmlEngines  = ["wkhtmltopdf", "weasyprint", "prince"]
@@ -159,95 +140,15 @@
                   "FILE")
                  "" -- "Name of output file"
 
-    , Option "" ["data-dir"]
-                 (ReqArg
-                  (\arg opt -> return opt { optDataDir =
-                                  Just (normalizePath arg) })
-                 "DIRECTORY") -- "Directory containing pandoc data files."
-                ""
-
-    , Option "" ["base-header-level"]
-                 (ReqArg
-                  (\arg opt ->
-                      case safeRead arg of
-                           Just t | t > 0 && t < 6 ->
-                               return opt{ optBaseHeaderLevel = t }
-                           _              -> E.throwIO $ PandocOptionError
-                                               "base-header-level must be 1-5")
-                  "NUMBER")
-                 "" -- "Headers base level"
-
-    , Option "" ["strip-empty-paragraphs"]
-                 (NoArg
-                  (\opt -> do
-                      deprecatedOption "--stripEmptyParagraphs"
-                        "Use +empty_paragraphs extension."
-                      return opt{ optStripEmptyParagraphs = True }))
-                 "" -- "Strip empty paragraphs"
-
-    , Option "" ["indented-code-classes"]
-                  (ReqArg
-                   (\arg opt -> return opt { optIndentedCodeClasses = words $
-                                             map (\c -> if c == ',' then ' ' else c) arg })
-                   "STRING")
-                  "" -- "Classes (whitespace- or comma-separated) to use for indented code-blocks"
-
-    , Option "F" ["filter"]
-                 (ReqArg
-                  (\arg opt -> return opt { optFilters =
-                                    JSONFilter (normalizePath arg) :
-                                    optFilters opt })
-                  "PROGRAM")
-                 "" -- "External JSON filter"
-
-    , Option "" ["lua-filter"]
-                 (ReqArg
-                  (\arg opt -> return opt { optFilters =
-                                    LuaFilter (normalizePath arg) :
-                                    optFilters opt })
-                  "SCRIPTPATH")
-                 "" -- "Lua filter"
-
-    , Option "p" ["preserve-tabs"]
-                 (NoArg
-                  (\opt -> return opt { optPreserveTabs = True }))
-                 "" -- "Preserve tabs instead of converting to spaces"
-
-    , Option "" ["tab-stop"]
-                 (ReqArg
-                  (\arg opt ->
-                      case safeRead arg of
-                           Just t | t > 0 -> return opt { optTabStop = t }
-                           _              -> E.throwIO $ PandocOptionError
-                                  "tab-stop must be a number greater than 0")
-                  "NUMBER")
-                 "" -- "Tab stop (default 4)"
-
-    , Option "" ["track-changes"]
-                 (ReqArg
-                  (\arg opt -> do
-                     action <- case arg of
-                            "accept" -> return AcceptChanges
-                            "reject" -> return RejectChanges
-                            "all"    -> return AllChanges
-                            _        -> E.throwIO $ PandocOptionError
-                               ("Unknown option for track-changes: " ++ arg)
-                     return opt { optTrackChanges = action })
-                  "accept|reject|all")
-                 "" -- "Accepting or reject MS Word track-changes.""
-
-    , Option "" ["file-scope"]
-                 (NoArg
-                  (\opt -> return opt { optFileScope = True }))
-                 "" -- "Parse input files before combining"
-
-    , Option "" ["extract-media"]
+    , Option "" ["wrap"]
                  (ReqArg
                   (\arg opt ->
-                    return opt { optExtractMedia =
-                                  Just (normalizePath arg) })
-                  "PATH")
-                 "" -- "Directory to which to extract embedded media"
+                    case safeRead ("Wrap" ++ uppercaseFirstLetter arg) of
+                          Just o   -> return opt { optWrapText = o }
+                          Nothing  -> E.throwIO $ PandocOptionError
+                                     "--wrap must be auto, none, or preserve")
+                 "auto|none|preserve")
+                 "" -- "Option for wrapping text in output"
 
     , Option "s" ["standalone"]
                  (NoArg
@@ -262,6 +163,13 @@
                   "FILE")
                  "" -- "Use custom template"
 
+    , Option "" ["data-dir"]
+                 (ReqArg
+                  (\arg opt -> return opt { optDataDir =
+                                  Just (normalizePath arg) })
+                 "DIRECTORY") -- "Directory containing pandoc data files."
+                ""
+
     , Option "M" ["metadata"]
                  (ReqArg
                   (\arg opt -> do
@@ -285,53 +193,120 @@
                   "KEY[:VALUE]")
                  ""
 
-    , Option "D" ["print-default-template"]
+    , Option "" ["ascii"]
+                 (NoArg
+                  (\opt -> return opt { optAscii = True }))
+                 ""  -- "Prefer ASCII output"
+
+    , Option "" ["toc", "table-of-contents"]
+                (NoArg
+                 (\opt -> return opt { optTableOfContents = True }))
+               "" -- "Include table of contents"
+
+    , Option "" ["toc-depth"]
                  (ReqArg
-                  (\arg _ -> do
-                     templ <- runIO $ do
-                                setUserDataDir Nothing
-                                getDefaultTemplate arg
-                     case templ of
-                          Right "" -> -- e.g. for docx, odt, json:
-                            E.throwIO $ PandocCouldNotFindDataFileError
-                               ("templates/default." ++ arg)
-                          Right t -> UTF8.hPutStr stdout t
-                          Left e  -> E.throwIO e
-                     exitSuccess)
-                  "FORMAT")
-                 "" -- "Print default template for FORMAT"
+                  (\arg opt ->
+                      case safeRead arg of
+                           Just t | t >= 1 && t <= 6 ->
+                                    return opt { optTOCDepth = t }
+                           _      -> E.throwIO $ PandocOptionError
+                                    "TOC level must be a number between 1 and 6")
+                 "NUMBER")
+                 "" -- "Number of levels to include in TOC"
 
-    , Option "" ["print-default-data-file"]
+    , Option "N" ["number-sections"]
+                 (NoArg
+                  (\opt -> return opt { optNumberSections = True }))
+                 "" -- "Number sections in LaTeX"
+
+    , Option "" ["number-offset"]
                  (ReqArg
-                  (\arg _ -> do
-                     runIOorExplode $
-                       readDefaultDataFile arg >>= liftIO . BS.hPutStr stdout
-                     exitSuccess)
+                  (\arg opt ->
+                      case safeRead ('[':arg ++ "]") of
+                           Just ns -> return opt { optNumberOffset = ns,
+                                                   optNumberSections = True }
+                           _      -> E.throwIO $ PandocOptionError
+                                       "could not parse number-offset")
+                 "NUMBERS")
+                 "" -- "Starting number for sections, subsections, etc."
+
+    , Option "" ["top-level-division"]
+                 (ReqArg
+                  (\arg opt -> do
+                      let tldName = "TopLevel" ++ uppercaseFirstLetter arg
+                      case safeRead tldName of
+                        Just tlDiv -> return opt { optTopLevelDivision = tlDiv }
+                        _       -> E.throwIO $ PandocOptionError
+                                     ("Top-level division must be " ++
+                                      "section,  chapter, part, or default"))
+                   "section|chapter|part")
+                 "" -- "Use top-level division type in LaTeX, ConTeXt, DocBook"
+
+    , Option "" ["extract-media"]
+                 (ReqArg
+                  (\arg opt ->
+                    return opt { optExtractMedia =
+                                  Just (normalizePath arg) })
+                  "PATH")
+                 "" -- "Directory to which to extract embedded media"
+
+    , Option "" ["resource-path"]
+                (ReqArg
+                  (\arg opt -> return opt { optResourcePath =
+                                   splitSearchPath arg })
+                   "SEARCHPATH")
+                  "" -- "Paths to search for images and other resources"
+
+    , Option "H" ["include-in-header"]
+                 (ReqArg
+                  (\arg opt -> return opt{ optIncludeInHeader =
+                                              arg : optIncludeInHeader opt,
+                                            optStandalone = True })
                   "FILE")
-                  "" -- "Print default data file"
+                 "" -- "File to include at end of header (implies -s)"
 
-    , Option "" ["print-highlight-style"]
+    , Option "B" ["include-before-body"]
                  (ReqArg
-                  (\arg _ -> do
-                     sty <- fromMaybe pygments <$> lookupHighlightStyle arg
-                     B.putStr $ encodePretty'
-                       defConfig{confIndent = Spaces 4
-                                ,confCompare = keyOrder
-                                  (map T.pack
-                                   ["text-color"
-                                   ,"background-color"
-                                   ,"line-number-color"
-                                   ,"line-number-background-color"
-                                   ,"bold"
-                                   ,"italic"
-                                   ,"underline"
-                                   ,"text-styles"])
-                                ,confNumFormat = Generic
-                                ,confTrailingNewline = True} sty
-                     exitSuccess)
-                  "STYLE|FILE")
-                 "" -- "Print default template for FORMAT"
+                  (\arg opt -> return opt{ optIncludeBeforeBody =
+                                              arg : optIncludeBeforeBody opt,
+                                           optStandalone = True })
+                  "FILE")
+                 "" -- "File to include before document body"
 
+    , Option "A" ["include-after-body"]
+                 (ReqArg
+                  (\arg opt -> return opt{ optIncludeAfterBody =
+                                              arg : optIncludeAfterBody opt,
+                                           optStandalone = True })
+                  "FILE")
+                 "" -- "File to include after document body"
+
+    , Option "" ["no-highlight"]
+                (NoArg
+                 (\opt -> return opt { optHighlightStyle = Nothing }))
+                 "" -- "Don't highlight source code"
+
+    , Option "" ["highlight-style"]
+                (ReqArg
+                 (\arg opt -> lookupHighlightStyle arg >>= \style ->
+                     return opt{ optHighlightStyle = style })
+                 "STYLE|FILE")
+                 "" -- "Style for highlighted code"
+
+    , Option "" ["syntax-definition"]
+                (ReqArg
+                 (\arg opt -> do
+                   let tr c d = map (\x -> if x == c then d else x)
+                   let arg' = case arg of -- see #4836
+                                   -- HXT confuses Windows path with URI
+                                   _:':':'\\':_ ->
+                                       "file:///" ++ tr '\\' '/' arg
+                                   _ -> normalizePath arg
+                   return opt{ optSyntaxDefinitions = arg' :
+                                optSyntaxDefinitions opt })
+                 "FILE")
+                "" -- "Syntax definition (xml) file"
+
     , Option "" ["dpi"]
                  (ReqArg
                   (\arg opt ->
@@ -355,16 +330,6 @@
                   "crlf|lf|native")
                  "" -- "EOL (default OS-dependent)"
 
-    , Option "" ["wrap"]
-                 (ReqArg
-                  (\arg opt ->
-                    case safeRead ("Wrap" ++ uppercaseFirstLetter arg) of
-                          Just o   -> return opt { optWrapText = o }
-                          Nothing  -> E.throwIO $ PandocOptionError
-                                     "--wrap must be auto, none, or preserve")
-                 "auto|none|preserve")
-                 "" -- "Option for wrapping text in output"
-
     , Option "" ["columns"]
                  (ReqArg
                   (\arg opt ->
@@ -375,83 +340,52 @@
                  "NUMBER")
                  "" -- "Length of line in characters"
 
-    , Option "" ["strip-comments"]
-                (NoArg
-                 (\opt -> return opt { optStripComments = True }))
-               "" -- "Strip HTML comments"
-
-    , Option "" ["toc", "table-of-contents"]
-                (NoArg
-                 (\opt -> return opt { optTableOfContents = True }))
-               "" -- "Include table of contents"
+    , Option "p" ["preserve-tabs"]
+                 (NoArg
+                  (\opt -> return opt { optPreserveTabs = True }))
+                 "" -- "Preserve tabs instead of converting to spaces"
 
-    , Option "" ["toc-depth"]
+    , Option "" ["tab-stop"]
                  (ReqArg
                   (\arg opt ->
                       case safeRead arg of
-                           Just t | t >= 1 && t <= 6 ->
-                                    return opt { optTOCDepth = t }
-                           _      -> E.throwIO $ PandocOptionError
-                                    "TOC level must be a number between 1 and 6")
-                 "NUMBER")
-                 "" -- "Number of levels to include in TOC"
-
-    , Option "" ["no-highlight"]
-                (NoArg
-                 (\opt -> return opt { optHighlightStyle = Nothing }))
-                 "" -- "Don't highlight source code"
-
-    , Option "" ["highlight-style"]
-                (ReqArg
-                 (\arg opt -> lookupHighlightStyle arg >>= \style ->
-                     return opt{ optHighlightStyle = style })
-                 "STYLE|FILE")
-                 "" -- "Style for highlighted code"
-
-    , Option "" ["syntax-definition"]
-                (ReqArg
-                 (\arg opt -> do
-                   let tr c d = map (\x -> if x == c then d else x)
-                   let arg' = case arg of -- see #4836
-                                   -- HXT confuses Windows path with URI
-                                   _:':':'\\':_ ->
-                                       "file:///" ++ tr '\\' '/' arg
-                                   _ -> normalizePath arg
-                   return opt{ optSyntaxDefinitions = arg' :
-                                optSyntaxDefinitions opt })
-                 "FILE")
-                "" -- "Syntax definition (xml) file"
+                           Just t | t > 0 -> return opt { optTabStop = t }
+                           _              -> E.throwIO $ PandocOptionError
+                                  "tab-stop must be a number greater than 0")
+                  "NUMBER")
+                 "" -- "Tab stop (default 4)"
 
-    , Option "H" ["include-in-header"]
+    , Option "" ["pdf-engine"]
                  (ReqArg
-                  (\arg opt -> return opt{ optIncludeInHeader =
-                                              arg : optIncludeInHeader opt,
-                                            optStandalone = True })
-                  "FILE")
-                 "" -- "File to include at end of header (implies -s)"
+                  (\arg opt -> do
+                     let b = takeBaseName arg
+                     if b `elem` pdfEngines
+                        then return opt { optPdfEngine = Just arg }
+                        else E.throwIO $ PandocOptionError $ "pdf-engine must be one of "
+                               ++ intercalate ", " pdfEngines)
+                  "PROGRAM")
+                 "" -- "Name of program to use in generating PDF"
 
-    , Option "B" ["include-before-body"]
+    , Option "" ["pdf-engine-opt"]
                  (ReqArg
-                  (\arg opt -> return opt{ optIncludeBeforeBody =
-                                              arg : optIncludeBeforeBody opt,
-                                           optStandalone = True })
-                  "FILE")
-                 "" -- "File to include before document body"
+                  (\arg opt -> do
+                      let oldArgs = optPdfEngineArgs opt
+                      return opt { optPdfEngineArgs = oldArgs ++ [arg]})
+                  "STRING")
+                 "" -- "Flags to pass to the PDF-engine, all instances of this option are accumulated and used"
 
-    , Option "A" ["include-after-body"]
+    , Option "" ["reference-doc"]
                  (ReqArg
-                  (\arg opt -> return opt{ optIncludeAfterBody =
-                                              arg : optIncludeAfterBody opt,
-                                           optStandalone = True })
+                  (\arg opt ->
+                    return opt { optReferenceDoc = Just arg })
                   "FILE")
-                 "" -- "File to include after document body"
+                 "" -- "Path of custom reference doc"
 
-    , Option "" ["resource-path"]
-                (ReqArg
-                  (\arg opt -> return opt { optResourcePath =
-                                   splitSearchPath arg })
-                   "SEARCHPATH")
-                  "" -- "Paths to search for images and other resources"
+    , Option "" ["self-contained"]
+                 (NoArg
+                  (\opt -> return opt { optSelfContained = True,
+                                        optStandalone = True }))
+                 "" -- "Make slide shows include all the needed js and css"
 
     , Option "" ["request-header"]
                  (ReqArg
@@ -462,23 +396,83 @@
                   "NAME:VALUE")
                  ""
 
-    , Option "" ["self-contained"]
+    , Option "" ["file-scope"]
                  (NoArg
-                  (\opt -> return opt { optSelfContained = True,
-                                        optStandalone = True }))
-                 "" -- "Make slide shows include all the needed js and css"
+                  (\opt -> return opt { optFileScope = True }))
+                 "" -- "Parse input files before combining"
 
-    , Option "" ["html-q-tags"]
-                 (NoArg
-                  (\opt ->
-                     return opt { optHtmlQTags = True }))
-                 "" -- "Use <q> tags for quotes in HTML"
+    , Option "" ["abbreviations"]
+                (ReqArg
+                 (\arg opt -> return opt { optAbbreviations = Just arg })
+                "FILE")
+                "" -- "Specify file for custom abbreviations"
 
-    , Option "" ["ascii"]
+    , Option "" ["indented-code-classes"]
+                  (ReqArg
+                   (\arg opt -> return opt { optIndentedCodeClasses = words $
+                                             map (\c -> if c == ',' then ' ' else c) arg })
+                   "STRING")
+                  "" -- "Classes (whitespace- or comma-separated) to use for indented code-blocks"
+
+    , Option "" ["default-image-extension"]
+                 (ReqArg
+                  (\arg opt -> return opt { optDefaultImageExtension = arg })
+                   "extension")
+                  "" -- "Default extension for extensionless images"
+
+    , Option "F" ["filter"]
+                 (ReqArg
+                  (\arg opt -> return opt { optFilters =
+                                    JSONFilter (normalizePath arg) :
+                                    optFilters opt })
+                  "PROGRAM")
+                 "" -- "External JSON filter"
+
+    , Option "" ["lua-filter"]
+                 (ReqArg
+                  (\arg opt -> return opt { optFilters =
+                                    LuaFilter (normalizePath arg) :
+                                    optFilters opt })
+                  "SCRIPTPATH")
+                 "" -- "Lua filter"
+
+    , Option "" ["base-header-level"]
+                 (ReqArg
+                  (\arg opt ->
+                      case safeRead arg of
+                           Just t | t > 0 && t < 6 ->
+                               return opt{ optBaseHeaderLevel = t }
+                           _              -> E.throwIO $ PandocOptionError
+                                               "base-header-level must be 1-5")
+                  "NUMBER")
+                 "" -- "Headers base level"
+
+    , Option "" ["strip-empty-paragraphs"]
                  (NoArg
-                  (\opt -> return opt { optAscii = True }))
-                 ""  -- "Prefer ASCII output"
+                  (\opt -> do
+                      deprecatedOption "--stripEmptyParagraphs"
+                        "Use +empty_paragraphs extension."
+                      return opt{ optStripEmptyParagraphs = True }))
+                 "" -- "Strip empty paragraphs"
 
+    , Option "" ["track-changes"]
+                 (ReqArg
+                  (\arg opt -> do
+                     action <- case arg of
+                            "accept" -> return AcceptChanges
+                            "reject" -> return RejectChanges
+                            "all"    -> return AllChanges
+                            _        -> E.throwIO $ PandocOptionError
+                               ("Unknown option for track-changes: " ++ arg)
+                     return opt { optTrackChanges = action })
+                  "accept|reject|all")
+                 "" -- "Accepting or reject MS Word track-changes.""
+
+    , Option "" ["strip-comments"]
+                (NoArg
+                 (\opt -> return opt { optStripComments = True }))
+               "" -- "Strip HTML comments"
+
     , Option "" ["reference-links"]
                  (NoArg
                   (\opt -> return opt { optReferenceLinks = True } ))
@@ -502,34 +496,6 @@
                   (\opt -> return opt { optSetextHeaders = False } ))
                  "" -- "Use atx-style headers for markdown"
 
-    , Option "" ["top-level-division"]
-                 (ReqArg
-                  (\arg opt -> do
-                      let tldName = "TopLevel" ++ uppercaseFirstLetter arg
-                      case safeRead tldName of
-                        Just tlDiv -> return opt { optTopLevelDivision = tlDiv }
-                        _       -> E.throwIO $ PandocOptionError
-                                     ("Top-level division must be " ++
-                                      "section,  chapter, part, or default"))
-                   "section|chapter|part")
-                 "" -- "Use top-level division type in LaTeX, ConTeXt, DocBook"
-
-    , Option "N" ["number-sections"]
-                 (NoArg
-                  (\opt -> return opt { optNumberSections = True }))
-                 "" -- "Number sections in LaTeX"
-
-    , Option "" ["number-offset"]
-                 (ReqArg
-                  (\arg opt ->
-                      case safeRead ('[':arg ++ "]") of
-                           Just ns -> return opt { optNumberOffset = ns,
-                                                   optNumberSections = True }
-                           _      -> E.throwIO $ PandocOptionError
-                                       "could not parse number-offset")
-                 "NUMBERS")
-                 "" -- "Starting number for sections, subsections, etc."
-
     , Option "" ["listings"]
                  (NoArg
                   (\opt -> return opt { optListings = True }))
@@ -556,11 +522,11 @@
                   (\opt -> return opt { optSectionDivs = True }))
                  "" -- "Put sections in div tags in HTML"
 
-    , Option "" ["default-image-extension"]
-                 (ReqArg
-                  (\arg opt -> return opt { optDefaultImageExtension = arg })
-                   "extension")
-                  "" -- "Default extension for extensionless images"
+    , Option "" ["html-q-tags"]
+                 (NoArg
+                  (\opt ->
+                     return opt { optHtmlQTags = True }))
+                 "" -- "Use <q> tags for quotes in HTML"
 
     , Option "" ["email-obfuscation"]
                  (ReqArg
@@ -597,13 +563,6 @@
                   "URL")
                  "" -- "Link to CSS style sheet"
 
-    , Option "" ["reference-doc"]
-                 (ReqArg
-                  (\arg opt ->
-                    return opt { optReferenceDoc = Just arg })
-                  "FILE")
-                 "" -- "Path of custom reference doc"
-
     , Option "" ["epub-subdirectory"]
              (ReqArg
                   (\arg opt ->
@@ -643,24 +602,15 @@
                  "NUMBER")
                  "" -- "Header level at which to split chapters in EPUB"
 
-    , Option "" ["pdf-engine"]
-                 (ReqArg
-                  (\arg opt -> do
-                     let b = takeBaseName arg
-                     if b `elem` pdfEngines
-                        then return opt { optPdfEngine = Just arg }
-                        else E.throwIO $ PandocOptionError $ "pdf-engine must be one of "
-                               ++ intercalate ", " pdfEngines)
-                  "PROGRAM")
-                 "" -- "Name of program to use in generating PDF"
-
-    , Option "" ["pdf-engine-opt"]
+    , Option "" ["ipynb-output"]
                  (ReqArg
-                  (\arg opt -> do
-                      let oldArgs = optPdfEngineArgs opt
-                      return opt { optPdfEngineArgs = oldArgs ++ [arg]})
-                  "STRING")
-                 "" -- "Flags to pass to the PDF-engine, all instances of this option are accumulated and used"
+                  (\arg opt ->
+                    if arg `notElem` ["all","none","best"]
+                       then E.throwIO $ PandocOptionError $
+                             "ipynb-output must be all, none, or best"
+                       else return opt { optIpynbOutput = arg })
+                 "all|none|best")
+                 "" -- "Starting number for sections, subsections, etc."
 
     , Option "" ["bibliography"]
                  (ReqArg
@@ -733,12 +683,6 @@
                       return opt { optHTMLMathMethod = GladTeX }))
                  "" -- "Use gladtex for HTML math"
 
-    , Option "" ["abbreviations"]
-                (ReqArg
-                 (\arg opt -> return opt { optAbbreviations = Just arg })
-                "FILE")
-                "" -- "Specify file for custom abbreviations"
-
     , Option "" ["trace"]
                  (NoArg
                   (\opt -> return opt { optTrace = True }))
@@ -840,17 +784,63 @@
                      exitSuccess ))
                  ""
 
+    , Option "D" ["print-default-template"]
+                 (ReqArg
+                  (\arg _ -> do
+                     templ <- runIO $ do
+                                setUserDataDir Nothing
+                                getDefaultTemplate arg
+                     case templ of
+                          Right "" -> -- e.g. for docx, odt, json:
+                            E.throwIO $ PandocCouldNotFindDataFileError
+                               ("templates/default." ++ arg)
+                          Right t -> UTF8.hPutStr stdout t
+                          Left e  -> E.throwIO e
+                     exitSuccess)
+                  "FORMAT")
+                 "" -- "Print default template for FORMAT"
+
+    , Option "" ["print-default-data-file"]
+                 (ReqArg
+                  (\arg _ -> do
+                     runIOorExplode $
+                       readDefaultDataFile arg >>= liftIO . BS.hPutStr stdout
+                     exitSuccess)
+                  "FILE")
+                  "" -- "Print default data file"
+
+    , Option "" ["print-highlight-style"]
+                 (ReqArg
+                  (\arg _ -> do
+                     sty <- fromMaybe pygments <$> lookupHighlightStyle arg
+                     B.putStr $ encodePretty'
+                       defConfig{confIndent = Spaces 4
+                                ,confCompare = keyOrder
+                                  (map T.pack
+                                   ["text-color"
+                                   ,"background-color"
+                                   ,"line-number-color"
+                                   ,"line-number-background-color"
+                                   ,"bold"
+                                   ,"italic"
+                                   ,"underline"
+                                   ,"text-styles"])
+                                ,confNumFormat = Generic
+                                ,confTrailingNewline = True} sty
+                     exitSuccess)
+                  "STYLE|FILE")
+                 "" -- "Print default template for FORMAT"
+
+
     , Option "v" ["version"]
                  (NoArg
                   (\_ -> do
                      prg <- getProgName
-                     defaultDatadir <- E.catch
-                            (getAppUserDataDirectory "pandoc")
-                            (\e -> let _ = (e :: E.SomeException)
-                                   in  return "")
+                     defaultDatadirs <- defaultUserDataDirs
                      UTF8.hPutStrLn stdout (prg ++ " " ++ pandocVersion ++
                        compileInfo ++ "\nDefault user data directory: " ++
-                       defaultDatadir ++ copyrightMessage)
+                       intercalate " or " defaultDatadirs ++
+                       ('\n':copyrightMessage))
                      exitSuccess ))
                  "" -- "Print version"
 
@@ -879,7 +869,6 @@
 
 copyrightMessage :: String
 copyrightMessage = intercalate "\n" [
-  "",
   "Copyright (C) 2006-2019 John MacFarlane",
   "Web:  http://pandoc.org",
   "This is free software; see the source for copying conditions.",
diff --git a/src/Text/Pandoc/App/FormatHeuristics.hs b/src/Text/Pandoc/App/FormatHeuristics.hs
--- a/src/Text/Pandoc/App/FormatHeuristics.hs
+++ b/src/Text/Pandoc/App/FormatHeuristics.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-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.App.FormatHeuristics
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley@edu>
diff --git a/src/Text/Pandoc/App/Opt.hs b/src/Text/Pandoc/App/Opt.hs
--- a/src/Text/Pandoc/App/Opt.hs
+++ b/src/Text/Pandoc/App/Opt.hs
@@ -4,27 +4,9 @@
 #ifdef DERIVE_JSON_VIA_TH
 {-# LANGUAGE TemplateHaskell     #-}
 #endif
-{-
-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.App.Opt
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley@edu>
@@ -123,6 +105,7 @@
     , optFileScope             :: Bool         -- ^ Parse input files before combining
     , optTitlePrefix           :: Maybe String     -- ^ Prefix for title
     , optCss                   :: [FilePath]       -- ^ CSS files to link to
+    , optIpynbOutput           :: String           -- ^ Maybe f to use best data; Nothing to omit
     , optIncludeBeforeBody     :: [FilePath]       -- ^ Files to include before
     , optIncludeAfterBody      :: [FilePath]       -- ^ Files to include after body
     , optIncludeInHeader       :: [FilePath]       -- ^ Files to include in header
@@ -196,6 +179,7 @@
     , optFileScope             = False
     , optTitlePrefix           = Nothing
     , optCss                   = []
+    , optIpynbOutput           = "best"
     , optIncludeBeforeBody     = []
     , optIncludeAfterBody      = []
     , optIncludeInHeader       = []
diff --git a/src/Text/Pandoc/App/OutputSettings.hs b/src/Text/Pandoc/App/OutputSettings.hs
--- a/src/Text/Pandoc/App/OutputSettings.hs
+++ b/src/Text/Pandoc/App/OutputSettings.hs
@@ -3,27 +3,9 @@
 {-# LANGUAGE NoImplicitPrelude   #-}
 {-# LANGUAGE ScopedTypeVariables #-}
 {-# LANGUAGE TupleSections       #-}
-{-
-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.App
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley@edu>
diff --git a/src/Text/Pandoc/Asciify.hs b/src/Text/Pandoc/Asciify.hs
--- a/src/Text/Pandoc/Asciify.hs
+++ b/src/Text/Pandoc/Asciify.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-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.Asciify
-   Copyright   : Copyright (C) 2013-2018 John MacFarlane
+   Copyright   : Copyright (C) 2013-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/BCP47.hs b/src/Text/Pandoc/BCP47.hs
--- a/src/Text/Pandoc/BCP47.hs
+++ b/src/Text/Pandoc/BCP47.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2017–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.BCP47
-   Copyright   : Copyright (C) 2017–2018 John MacFarlane
+   Copyright   : Copyright (C) 2017–2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/CSS.hs b/src/Text/Pandoc/CSS.hs
--- a/src/Text/Pandoc/CSS.hs
+++ b/src/Text/Pandoc/CSS.hs
@@ -1,4 +1,17 @@
 {-# LANGUAGE NoImplicitPrelude #-}
+{- |
+Module      : Text.Pandoc.CSS
+Copyright   : © 2006-2019 John MacFarlane <jgm@berkeley.edu>,
+                2015-2016 Mauro Bieg,
+                2015      Ophir Lifshitz <hangfromthefloor@gmail.com>
+License     : GNU GPL, version 2 or above
+
+Maintainer  : John MacFarlane <jgm@berkeley@edu>
+Stability   : alpha
+Portability : portable
+
+Tools for working with CSS.
+-}
 module Text.Pandoc.CSS ( foldOrElse
                        , pickStyleAttrProps
                        , pickStylesToKVs
diff --git a/src/Text/Pandoc/CSV.hs b/src/Text/Pandoc/CSV.hs
--- a/src/Text/Pandoc/CSV.hs
+++ b/src/Text/Pandoc/CSV.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2017–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.CSV
-   Copyright   : Copyright (C) 2017–2018 John MacFarlane <jgm@berkeley.edu>
+   Copyright   : Copyright (C) 2017–2019 John MacFarlane <jgm@berkeley.edu>
    License     : GNU GPL, version 2 or above
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
    Stability   : alpha
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
@@ -13,26 +13,6 @@
 #else
 {-# LANGUAGE OverlappingInstances #-}
 #endif
-
-{-
-Copyright (C) 2016-17 Jesse Rosenthal <jrosenthal@jhu.edu>
-and John MacFarlane.
-
-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.Class
    Copyright   : Copyright (C) 2016-17 Jesse Rosenthal, John MacFarlane
diff --git a/src/Text/Pandoc/Data.hs b/src/Text/Pandoc/Data.hs
--- a/src/Text/Pandoc/Data.hs
+++ b/src/Text/Pandoc/Data.hs
@@ -1,6 +1,16 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE TemplateHaskell #-}
+{- |
+Module      : Text.Pandoc.Data
+Copyright   : Copyright (C) 2013-2019 John MacFarlane
+License     : GNU GPL, version 2 or above
 
+Maintainer  : John MacFarlane <jgm@berkeley@edu>
+Stability   : alpha
+Portability : portable
+
+Provide contents data files as Haskell values.
+-}
 module Text.Pandoc.Data (dataFiles) where
 
 import Prelude
diff --git a/src/Text/Pandoc/Emoji.hs b/src/Text/Pandoc/Emoji.hs
--- a/src/Text/Pandoc/Emoji.hs
+++ b/src/Text/Pandoc/Emoji.hs
@@ -1,22 +1,4 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2015 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.Emoji
    Copyright   : Copyright (C) 2015 John MacFarlane
diff --git a/src/Text/Pandoc/Error.hs b/src/Text/Pandoc/Error.hs
--- a/src/Text/Pandoc/Error.hs
+++ b/src/Text/Pandoc/Error.hs
@@ -1,26 +1,9 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE DeriveDataTypeable #-}
 {-# LANGUAGE DeriveGeneric      #-}
-{-
-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.Error
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
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
@@ -6,27 +6,9 @@
 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
 {-# LANGUAGE TemplateHaskell            #-}
 #endif
-{-
-Copyright (C) 2012-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.Extensions
-   Copyright   : Copyright (C) 2012-2018 John MacFarlane
+   Copyright   : Copyright (C) 2012-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -265,7 +247,7 @@
 -- | Extensions to be used with github-flavored markdown.
 githubMarkdownExtensions :: Extensions
 githubMarkdownExtensions = extensionsFromList
-  [ Ext_angle_brackets_escapable
+  [ Ext_all_symbols_escapable
   , Ext_pipe_tables
   , Ext_raw_html
   , Ext_fenced_code_blocks
@@ -332,8 +314,24 @@
 getDefaultExtensions "markdown_mmd" = multimarkdownExtensions
 getDefaultExtensions "markdown_github" = githubMarkdownExtensions
 getDefaultExtensions "markdown"        = pandocExtensions
-getDefaultExtensions "ipynb"           = enableExtension Ext_tex_math_dollars
-                                           githubMarkdownExtensions
+getDefaultExtensions "ipynb"           =
+  extensionsFromList
+    [ Ext_all_symbols_escapable
+    , Ext_pipe_tables
+    , Ext_raw_html
+    , Ext_fenced_code_blocks
+    , Ext_auto_identifiers
+    , Ext_gfm_auto_identifiers
+    , Ext_backtick_code_blocks
+    , Ext_autolink_bare_uris
+    , Ext_space_in_atx_header
+    , Ext_intraword_underscores
+    , Ext_strikeout
+    , Ext_task_lists
+    , Ext_lists_without_preceding_blankline
+    , Ext_shortcut_reference_links
+    , Ext_tex_math_dollars
+    ]
 getDefaultExtensions "muse"            = extensionsFromList
                                            [Ext_amuse,
                                             Ext_auto_identifiers]
diff --git a/src/Text/Pandoc/Filter.hs b/src/Text/Pandoc/Filter.hs
--- a/src/Text/Pandoc/Filter.hs
+++ b/src/Text/Pandoc/Filter.hs
@@ -4,26 +4,9 @@
 #ifdef DERIVE_JSON_VIA_TH
 {-# LANGUAGE TemplateHaskell   #-}
 #endif
-{-
-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.Filter
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley@edu>
diff --git a/src/Text/Pandoc/Filter/JSON.hs b/src/Text/Pandoc/Filter/JSON.hs
--- a/src/Text/Pandoc/Filter/JSON.hs
+++ b/src/Text/Pandoc/Filter/JSON.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-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.Filter
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley@edu>
diff --git a/src/Text/Pandoc/Filter/Lua.hs b/src/Text/Pandoc/Filter/Lua.hs
--- a/src/Text/Pandoc/Filter/Lua.hs
+++ b/src/Text/Pandoc/Filter/Lua.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-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.Filter.Lua
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley@edu>
diff --git a/src/Text/Pandoc/Filter/Path.hs b/src/Text/Pandoc/Filter/Path.hs
--- a/src/Text/Pandoc/Filter/Path.hs
+++ b/src/Text/Pandoc/Filter/Path.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-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.Filter.Path
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley@edu>
diff --git a/src/Text/Pandoc/Highlighting.hs b/src/Text/Pandoc/Highlighting.hs
--- a/src/Text/Pandoc/Highlighting.hs
+++ b/src/Text/Pandoc/Highlighting.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2008-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.Highlighting
-   Copyright   : Copyright (C) 2008-2018 John MacFarlane
+   Copyright   : Copyright (C) 2008-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/ImageSize.hs b/src/Text/Pandoc/ImageSize.hs
--- a/src/Text/Pandoc/ImageSize.hs
+++ b/src/Text/Pandoc/ImageSize.hs
@@ -1,27 +1,9 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings, ScopedTypeVariables, CPP #-}
 {-# OPTIONS_GHC -fno-warn-type-defaults #-}
-{-
-  Copyright (C) 2011-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.ImageSize
-Copyright   : Copyright (C) 2011-2018 John MacFarlane
+Copyright   : Copyright (C) 2011-2019 John MacFarlane
 License     : GNU GPL, version 2 or above
 
 Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Logging.hs b/src/Text/Pandoc/Logging.hs
--- a/src/Text/Pandoc/Logging.hs
+++ b/src/Text/Pandoc/Logging.hs
@@ -2,26 +2,9 @@
 {-# LANGUAGE DeriveDataTypeable #-}
 {-# LANGUAGE DeriveGeneric      #-}
 {-# LANGUAGE OverloadedStrings  #-}
-{-
-Copyright (C) 2016-17 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.Logging
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Lua.hs b/src/Text/Pandoc/Lua.hs
--- a/src/Text/Pandoc/Lua.hs
+++ b/src/Text/Pandoc/Lua.hs
@@ -1,24 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright © 2017–2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-
-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.Lua
-   Copyright   : Copyright © 2017–2018 Albert Krewinkel
+   Copyright   : Copyright © 2017–2019 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
@@ -39,5 +22,5 @@
 import Text.Pandoc.Lua.Filter (runFilterFile)
 import Text.Pandoc.Lua.Global (Global (..), setGlobals)
 import Text.Pandoc.Lua.Init (LuaException (..), runLua)
-import Text.Pandoc.Lua.StackInstances ()
+import Text.Pandoc.Lua.Marshaling ()
 
diff --git a/src/Text/Pandoc/Lua/Filter.hs b/src/Text/Pandoc/Lua/Filter.hs
--- a/src/Text/Pandoc/Lua/Filter.hs
+++ b/src/Text/Pandoc/Lua/Filter.hs
@@ -1,27 +1,9 @@
-{-
-Copyright © 2012-2018 John MacFarlane <jgm@berkeley.edu>
-            2017-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-
-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
--}
 {-# LANGUAGE FlexibleContexts #-}
 {-# LANGUAGE NoImplicitPrelude #-}
 {- |
 Module      : Text.Pandoc.Lua.Filter
-Copyright   : © 2012–2018 John MacFarlane,
-              © 2017-2018 Albert Krewinkel
+Copyright   : © 2012–2019 John MacFarlane,
+              © 2017-2019 Albert Krewinkel
 License     : GNU GPL, version 2 or above
 Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
 Stability   : alpha
@@ -48,7 +30,7 @@
 import Data.Map (Map)
 import Foreign.Lua (Lua, Peekable, Pushable)
 import Text.Pandoc.Definition
-import Text.Pandoc.Lua.StackInstances ()
+import Text.Pandoc.Lua.Marshaling ()
 import Text.Pandoc.Walk (walkM, Walkable)
 
 import qualified Data.Map.Strict as Map
diff --git a/src/Text/Pandoc/Lua/Global.hs b/src/Text/Pandoc/Lua/Global.hs
--- a/src/Text/Pandoc/Lua/Global.hs
+++ b/src/Text/Pandoc/Lua/Global.hs
@@ -1,25 +1,8 @@
 {-# LANGUAGE DeriveDataTypeable #-}
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright © 2017-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-
-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.Lua
-   Copyright   : Copyright © 2017-2018 Albert Krewinkel
+   Copyright   : Copyright © 2017-2019 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
@@ -41,7 +24,7 @@
 import Paths_pandoc (version)
 import Text.Pandoc.Class (CommonState)
 import Text.Pandoc.Definition (Pandoc (Pandoc), pandocTypesVersion)
-import Text.Pandoc.Lua.StackInstances ()
+import Text.Pandoc.Lua.Marshaling ()
 import Text.Pandoc.Lua.Util (addFunction)
 import Text.Pandoc.Options (ReaderOptions)
 
diff --git a/src/Text/Pandoc/Lua/Init.hs b/src/Text/Pandoc/Lua/Init.hs
--- a/src/Text/Pandoc/Lua/Init.hs
+++ b/src/Text/Pandoc/Lua/Init.hs
@@ -1,24 +1,7 @@
-{-
-Copyright © 2017-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-
-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
--}
 {-# LANGUAGE NoImplicitPrelude #-}
 {- |
    Module      : Text.Pandoc.Lua
-   Copyright   : Copyright © 2017-2018 Albert Krewinkel
+   Copyright   : Copyright © 2017-2019 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
@@ -36,11 +19,10 @@
 import Prelude
 import Control.Monad.Trans (MonadIO (..))
 import Data.Data (Data, dataTypeConstrs, dataTypeOf, showConstr)
-import Data.IORef (newIORef, readIORef)
 import Foreign.Lua (Lua)
 import GHC.IO.Encoding (getForeignEncoding, setForeignEncoding, utf8)
 import Text.Pandoc.Class (PandocIO, getCommonState, getUserDataDir,
-                          getMediaBag, setMediaBag)
+                          putCommonState)
 import Text.Pandoc.Lua.Global (Global (..), setGlobals)
 import Text.Pandoc.Lua.Packages (LuaPackageParams (..),
                                  installPandocPackageSearcher)
@@ -49,6 +31,7 @@
 import qualified Foreign.Lua as Lua
 import qualified Foreign.Lua.Module.Text as Lua
 import qualified Text.Pandoc.Definition as Pandoc
+import qualified Text.Pandoc.Lua.Module.Pandoc as ModulePandoc
 
 -- | Lua error message
 newtype LuaException = LuaException String deriving (Show)
@@ -63,13 +46,20 @@
   res <- liftIO . Lua.runEither $ do
     setGlobals globals
     initLuaState luaPkgParams
-    luaOp
+    -- run the given Lua operation
+    opResult <- luaOp
+    -- get the (possibly modified) state back
+    Lua.getglobal "PANDOC_STATE"
+    st <- Lua.peek Lua.stackTop
+    Lua.pop 1
+    -- done
+    return (opResult, st)
   liftIO $ setForeignEncoding enc
-  newMediaBag <- liftIO (readIORef (luaPkgMediaBag luaPkgParams))
-  setMediaBag newMediaBag
-  return $ case res of
-    Left (Lua.Exception msg) -> Left (LuaException msg)
-    Right x -> Right x
+  case res of
+    Left (Lua.Exception msg) -> return $ Left (LuaException msg)
+    Right (x, newState) -> do
+      putCommonState newState
+      return $ Right x
 
 -- | Global variables which should always be set.
 defaultGlobals :: PandocIO [Global]
@@ -84,27 +74,42 @@
 -- | Generate parameters required to setup pandoc's lua environment.
 luaPackageParams :: PandocIO LuaPackageParams
 luaPackageParams = do
-  commonState <- getCommonState
   datadir <- getUserDataDir
-  mbRef <- liftIO . newIORef =<< getMediaBag
-  return LuaPackageParams
-    { luaPkgCommonState = commonState
-    , luaPkgDataDir = datadir
-    , luaPkgMediaBag = mbRef
-    }
+  return LuaPackageParams { luaPkgDataDir = datadir }
 
 -- | Initialize the lua state with all required values
 initLuaState :: LuaPackageParams -> Lua ()
-initLuaState luaPkgParams = do
+initLuaState pkgParams = do
   Lua.openlibs
   Lua.preloadTextModule "text"
-  installPandocPackageSearcher luaPkgParams
-  loadScriptFromDataDir (luaPkgDataDir luaPkgParams) "init.lua"
-  putConstructorsInRegistry
+  installPandocPackageSearcher pkgParams
+  initPandocModule
+  loadScriptFromDataDir (luaPkgDataDir pkgParams) "init.lua"
+ where
+  initPandocModule :: Lua ()
+  initPandocModule = do
+    -- Push module table
+    ModulePandoc.pushModule (luaPkgDataDir pkgParams)
+    -- register as loaded module
+    Lua.pushvalue Lua.stackTop
+    Lua.getfield Lua.registryindex Lua.loadedTableRegistryField
+    Lua.setfield (Lua.nthFromTop 2) "pandoc"
+    Lua.pop 1
+    -- copy constructors into registry
+    putConstructorsInRegistry
+    -- assign module to global variable
+    Lua.setglobal "pandoc"
 
+-- | AST elements are marshaled via normal constructor functions in the
+-- @pandoc@ module. However, accessing Lua globals from Haskell is
+-- expensive (due to error handling). Accessing the Lua registry is much
+-- cheaper, which is why the constructor functions are copied into the
+-- Lua registry and called from there.
+--
+-- This function expects the @pandoc@ module to be at the top of the
+-- stack.
 putConstructorsInRegistry :: Lua ()
 putConstructorsInRegistry = do
-  Lua.getglobal "pandoc"
   constrsToReg $ Pandoc.Pandoc mempty mempty
   constrsToReg $ Pandoc.Str mempty
   constrsToReg $ Pandoc.Para mempty
@@ -113,7 +118,6 @@
   constrsToReg $ Pandoc.Citation mempty mempty mempty Pandoc.AuthorInText 0 0
   putInReg "Attr"  -- used for Attr type alias
   putInReg "ListAttributes"  -- used for ListAttributes type alias
-  Lua.pop 1
  where
   constrsToReg :: Data a => a -> Lua ()
   constrsToReg = mapM_ (putInReg . showConstr) . dataTypeConstrs . dataTypeOf
diff --git a/src/Text/Pandoc/Lua/Marshaling.hs b/src/Text/Pandoc/Lua/Marshaling.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Lua/Marshaling.hs
@@ -0,0 +1,16 @@
+{- |
+   Module      : Text.Pandoc.Lua.Marshaling
+   Copyright   : © 2012-2019 John MacFarlane
+                 © 2017-2019 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
+   Stability   : alpha
+
+Lua marshaling (pushing) and unmarshaling (peeking) instances.
+-}
+module Text.Pandoc.Lua.Marshaling () where
+
+import Text.Pandoc.Lua.Marshaling.AST ()
+import Text.Pandoc.Lua.Marshaling.CommonState ()
+import Text.Pandoc.Lua.Marshaling.ReaderOptions ()
diff --git a/src/Text/Pandoc/Lua/Marshaling/AST.hs b/src/Text/Pandoc/Lua/Marshaling/AST.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Lua/Marshaling/AST.hs
@@ -0,0 +1,312 @@
+{-# OPTIONS_GHC -fno-warn-orphans #-}
+{-# LANGUAGE NoImplicitPrelude    #-}
+{-# LANGUAGE FlexibleInstances    #-}
+{-# LANGUAGE ScopedTypeVariables  #-}
+{-# LANGUAGE LambdaCase           #-}
+{- |
+   Module      : Text.Pandoc.Lua.Marshaling.AST
+   Copyright   : © 2012-2019 John MacFarlane
+                 © 2017-2019 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
+   Stability   : alpha
+
+Marshaling/unmarshaling instances for document AST elements.
+-}
+module Text.Pandoc.Lua.Marshaling.AST () where
+
+import Prelude
+import Control.Applicative ((<|>))
+import Foreign.Lua (Lua, Peekable, Pushable, StackIndex)
+import Foreign.Lua.Userdata ( ensureUserdataMetatable, pushAnyWithMetatable
+                            , metatableName)
+import Text.Pandoc.Definition
+import Text.Pandoc.Lua.Util (defineHowTo, pushViaConstructor)
+import Text.Pandoc.Lua.Marshaling.CommonState ()
+import Text.Pandoc.Shared (Element (Blk, Sec))
+
+import qualified Foreign.Lua as Lua
+import qualified Text.Pandoc.Lua.Util as LuaUtil
+
+instance Pushable Pandoc where
+  push (Pandoc meta blocks) =
+    pushViaConstructor "Pandoc" blocks meta
+
+instance Peekable Pandoc where
+  peek idx = defineHowTo "get Pandoc value" $ do
+    blocks <- LuaUtil.rawField idx "blocks"
+    meta   <- LuaUtil.rawField idx "meta"
+    return $ Pandoc meta blocks
+
+instance Pushable Meta where
+  push (Meta mmap) =
+    pushViaConstructor "Meta" mmap
+instance Peekable Meta where
+  peek idx = defineHowTo "get Meta value" $
+    Meta <$> Lua.peek idx
+
+instance Pushable MetaValue where
+  push = pushMetaValue
+instance Peekable MetaValue where
+  peek = peekMetaValue
+
+instance Pushable Block where
+  push = pushBlock
+
+instance Peekable Block where
+  peek = peekBlock
+
+-- Inline
+instance Pushable Inline where
+  push = pushInline
+
+instance Peekable Inline where
+  peek = peekInline
+
+-- Citation
+instance Pushable Citation where
+  push (Citation cid prefix suffix mode noteNum hash) =
+    pushViaConstructor "Citation" cid mode prefix suffix noteNum hash
+
+instance Peekable Citation where
+  peek idx = do
+    id' <- LuaUtil.rawField idx "id"
+    prefix <- LuaUtil.rawField idx "prefix"
+    suffix <- LuaUtil.rawField idx "suffix"
+    mode <- LuaUtil.rawField idx "mode"
+    num <- LuaUtil.rawField idx "note_num"
+    hash <- LuaUtil.rawField idx "hash"
+    return $ Citation id' prefix suffix mode num hash
+
+instance Pushable Alignment where
+  push = Lua.push . show
+instance Peekable Alignment where
+  peek = Lua.peekRead
+
+instance Pushable CitationMode where
+  push = Lua.push . show
+instance Peekable CitationMode where
+  peek = Lua.peekRead
+
+instance Pushable Format where
+  push (Format f) = Lua.push f
+instance Peekable Format where
+  peek idx = Format <$> Lua.peek idx
+
+instance Pushable ListNumberDelim where
+  push = Lua.push . show
+instance Peekable ListNumberDelim where
+  peek = Lua.peekRead
+
+instance Pushable ListNumberStyle where
+  push = Lua.push . show
+instance Peekable ListNumberStyle where
+  peek = Lua.peekRead
+
+instance Pushable MathType where
+  push = Lua.push . show
+instance Peekable MathType where
+  peek = Lua.peekRead
+
+instance Pushable QuoteType where
+  push = Lua.push . show
+instance Peekable QuoteType where
+  peek = Lua.peekRead
+
+-- | Push an meta value element to the top of the lua stack.
+pushMetaValue :: MetaValue -> Lua ()
+pushMetaValue = \case
+  MetaBlocks blcks  -> pushViaConstructor "MetaBlocks" blcks
+  MetaBool bool     -> Lua.push bool
+  MetaInlines inlns -> pushViaConstructor "MetaInlines" inlns
+  MetaList metalist -> pushViaConstructor "MetaList" metalist
+  MetaMap metamap   -> pushViaConstructor "MetaMap" metamap
+  MetaString str    -> Lua.push str
+
+-- | Interpret the value at the given stack index as meta value.
+peekMetaValue :: StackIndex -> Lua MetaValue
+peekMetaValue idx = defineHowTo "get MetaValue" $ do
+  -- Get the contents of an AST element.
+  let elementContent :: Peekable a => Lua a
+      elementContent = Lua.peek idx
+  luatype <- Lua.ltype idx
+  case luatype of
+    Lua.TypeBoolean -> MetaBool <$> Lua.peek idx
+    Lua.TypeString  -> MetaString <$> Lua.peek idx
+    Lua.TypeTable   -> do
+      tag <- Lua.try $ LuaUtil.getTag idx
+      case tag of
+        Right "MetaBlocks"  -> MetaBlocks  <$> elementContent
+        Right "MetaBool"    -> MetaBool    <$> elementContent
+        Right "MetaMap"     -> MetaMap     <$> elementContent
+        Right "MetaInlines" -> MetaInlines <$> elementContent
+        Right "MetaList"    -> MetaList    <$> elementContent
+        Right "MetaString"  -> MetaString  <$> elementContent
+        Right t             -> Lua.throwException ("Unknown meta tag: " <> t)
+        Left _ -> do
+          -- no meta value tag given, try to guess.
+          len <- Lua.rawlen idx
+          if len <= 0
+            then MetaMap <$> Lua.peek idx
+            else  (MetaInlines <$> Lua.peek idx)
+                  <|> (MetaBlocks <$> Lua.peek idx)
+                  <|> (MetaList <$> Lua.peek idx)
+    _        -> Lua.throwException "could not get meta value"
+
+-- | Push an block element to the top of the lua stack.
+pushBlock :: Block -> Lua ()
+pushBlock = \case
+  BlockQuote blcks         -> pushViaConstructor "BlockQuote" blcks
+  BulletList items         -> pushViaConstructor "BulletList" items
+  CodeBlock attr code      -> pushViaConstructor "CodeBlock" code (LuaAttr attr)
+  DefinitionList items     -> pushViaConstructor "DefinitionList" items
+  Div attr blcks           -> pushViaConstructor "Div" blcks (LuaAttr attr)
+  Header lvl attr inlns    -> pushViaConstructor "Header" lvl inlns (LuaAttr attr)
+  HorizontalRule           -> pushViaConstructor "HorizontalRule"
+  LineBlock blcks          -> pushViaConstructor "LineBlock" blcks
+  OrderedList lstAttr list -> pushViaConstructor "OrderedList" list
+                                                 (LuaListAttributes lstAttr)
+  Null                     -> pushViaConstructor "Null"
+  Para blcks               -> pushViaConstructor "Para" blcks
+  Plain blcks              -> pushViaConstructor "Plain" blcks
+  RawBlock f cs            -> pushViaConstructor "RawBlock" f cs
+  Table capt aligns widths headers rows ->
+    pushViaConstructor "Table" capt aligns widths headers rows
+
+-- | Return the value at the given index as block if possible.
+peekBlock :: StackIndex -> Lua Block
+peekBlock idx = defineHowTo "get Block value" $ do
+  tag <- LuaUtil.getTag idx
+  case tag of
+      "BlockQuote"     -> BlockQuote <$> elementContent
+      "BulletList"     -> BulletList <$> elementContent
+      "CodeBlock"      -> withAttr CodeBlock <$> elementContent
+      "DefinitionList" -> DefinitionList <$> elementContent
+      "Div"            -> withAttr Div <$> elementContent
+      "Header"         -> (\(lvl, LuaAttr attr, lst) -> Header lvl attr lst)
+                          <$> elementContent
+      "HorizontalRule" -> return HorizontalRule
+      "LineBlock"      -> LineBlock <$> elementContent
+      "OrderedList"    -> (\(LuaListAttributes lstAttr, lst) ->
+                             OrderedList lstAttr lst)
+                          <$> elementContent
+      "Null"           -> return Null
+      "Para"           -> Para <$> elementContent
+      "Plain"          -> Plain <$> elementContent
+      "RawBlock"       -> uncurry RawBlock <$> elementContent
+      "Table"          -> (\(capt, aligns, widths, headers, body) ->
+                                  Table capt aligns widths headers body)
+                          <$> elementContent
+      _ -> Lua.throwException ("Unknown block type: " <> tag)
+ where
+   -- Get the contents of an AST element.
+   elementContent :: Peekable a => Lua a
+   elementContent = LuaUtil.rawField idx "c"
+
+-- | Push an inline element to the top of the lua stack.
+pushInline :: Inline -> Lua ()
+pushInline = \case
+  Cite citations lst       -> pushViaConstructor "Cite" lst citations
+  Code attr lst            -> pushViaConstructor "Code" lst (LuaAttr attr)
+  Emph inlns               -> pushViaConstructor "Emph" inlns
+  Image attr alt (src,tit) -> pushViaConstructor "Image" alt src tit (LuaAttr attr)
+  LineBreak                -> pushViaConstructor "LineBreak"
+  Link attr lst (src,tit)  -> pushViaConstructor "Link" lst src tit (LuaAttr attr)
+  Note blcks               -> pushViaConstructor "Note" blcks
+  Math mty str             -> pushViaConstructor "Math" mty str
+  Quoted qt inlns          -> pushViaConstructor "Quoted" qt inlns
+  RawInline f cs           -> pushViaConstructor "RawInline" f cs
+  SmallCaps inlns          -> pushViaConstructor "SmallCaps" inlns
+  SoftBreak                -> pushViaConstructor "SoftBreak"
+  Space                    -> pushViaConstructor "Space"
+  Span attr inlns          -> pushViaConstructor "Span" inlns (LuaAttr attr)
+  Str str                  -> pushViaConstructor "Str" str
+  Strikeout inlns          -> pushViaConstructor "Strikeout" inlns
+  Strong inlns             -> pushViaConstructor "Strong" inlns
+  Subscript inlns          -> pushViaConstructor "Subscript" inlns
+  Superscript inlns        -> pushViaConstructor "Superscript" inlns
+
+-- | Return the value at the given index as inline if possible.
+peekInline :: StackIndex -> Lua Inline
+peekInline idx = defineHowTo "get Inline value" $ do
+  tag <- LuaUtil.getTag idx
+  case tag of
+    "Cite"       -> uncurry Cite <$> elementContent
+    "Code"       -> withAttr Code <$> elementContent
+    "Emph"       -> Emph <$> elementContent
+    "Image"      -> (\(LuaAttr attr, lst, tgt) -> Image attr lst tgt)
+                    <$> elementContent
+    "Link"       -> (\(LuaAttr attr, lst, tgt) -> Link attr lst tgt)
+                    <$> elementContent
+    "LineBreak"  -> return LineBreak
+    "Note"       -> Note <$> elementContent
+    "Math"       -> uncurry Math <$> elementContent
+    "Quoted"     -> uncurry Quoted <$> elementContent
+    "RawInline"  -> uncurry RawInline <$> elementContent
+    "SmallCaps"  -> SmallCaps <$> elementContent
+    "SoftBreak"  -> return SoftBreak
+    "Space"      -> return Space
+    "Span"       -> withAttr Span <$> elementContent
+    "Str"        -> Str <$> elementContent
+    "Strikeout"  -> Strikeout <$> elementContent
+    "Strong"     -> Strong <$> elementContent
+    "Subscript"  -> Subscript <$> elementContent
+    "Superscript"-> Superscript <$> elementContent
+    _ -> Lua.throwException ("Unknown inline type: " <> tag)
+ where
+   -- Get the contents of an AST element.
+   elementContent :: Peekable a => Lua a
+   elementContent = LuaUtil.rawField idx "c"
+
+withAttr :: (Attr -> a -> b) -> (LuaAttr, a) -> b
+withAttr f (attributes, x) = f (fromLuaAttr attributes) x
+
+-- | Wrapper for Attr
+newtype LuaAttr = LuaAttr { fromLuaAttr :: Attr }
+
+instance Pushable LuaAttr where
+  push (LuaAttr (id', classes, kv)) =
+    pushViaConstructor "Attr" id' classes kv
+
+instance Peekable LuaAttr where
+  peek idx = defineHowTo "get Attr value" (LuaAttr <$> Lua.peek idx)
+
+-- | Wrapper for ListAttributes
+newtype LuaListAttributes = LuaListAttributes  ListAttributes
+
+instance Pushable LuaListAttributes where
+  push (LuaListAttributes (start, style, delimiter)) =
+    pushViaConstructor "ListAttributes" start style delimiter
+
+instance Peekable LuaListAttributes where
+  peek = defineHowTo "get ListAttributes value" .
+         fmap LuaListAttributes . Lua.peek
+
+--
+-- Hierarchical elements
+--
+instance Pushable Element where
+  push (Blk blk) = Lua.push blk
+  push sec = pushAnyWithMetatable pushElementMetatable sec
+   where
+    pushElementMetatable = ensureUserdataMetatable (metatableName sec) $
+                           LuaUtil.addFunction "__index" indexElement
+
+instance Peekable Element where
+  peek idx = Lua.ltype idx >>= \case
+    Lua.TypeUserdata -> Lua.peekAny idx
+    _                -> Blk <$> Lua.peek idx
+
+indexElement :: Element -> String -> Lua Lua.NumResults
+indexElement = \case
+  (Blk _) -> const (1 <$ Lua.pushnil) -- this shouldn't happen
+  (Sec lvl num attr label contents) -> fmap (return 1) . \case
+    "level"     -> Lua.push lvl
+    "numbering" -> Lua.push num
+    "attr"      -> Lua.push (LuaAttr attr)
+    "label"     -> Lua.push label
+    "contents"  -> Lua.push contents
+    "tag"       -> Lua.push "Sec"
+    "t"         -> Lua.push "Sec"
+    _           -> Lua.pushnil
diff --git a/src/Text/Pandoc/Lua/Marshaling/AnyValue.hs b/src/Text/Pandoc/Lua/Marshaling/AnyValue.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Lua/Marshaling/AnyValue.hs
@@ -0,0 +1,26 @@
+{-# LANGUAGE NoImplicitPrelude    #-}
+{- |
+   Module      : Text.Pandoc.Lua.Marshaling.AnyValue
+   Copyright   : © 2017-2019 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
+   Stability   : alpha
+
+Helper type to work with raw Lua stack indices instead of unmarshaled
+values.
+
+TODO: Most of this module should be abstracted, factored out, and go
+into HsLua.
+-}
+module Text.Pandoc.Lua.Marshaling.AnyValue (AnyValue (..)) where
+
+import Prelude
+import Foreign.Lua (Peekable (peek), StackIndex)
+
+-- | Dummy type to allow values of arbitrary Lua type. This just wraps
+-- stack indices, using it requires extra care.
+newtype AnyValue = AnyValue StackIndex
+
+instance Peekable AnyValue where
+  peek = return . AnyValue
diff --git a/src/Text/Pandoc/Lua/Marshaling/CommonState.hs b/src/Text/Pandoc/Lua/Marshaling/CommonState.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Lua/Marshaling/CommonState.hs
@@ -0,0 +1,102 @@
+{-# OPTIONS_GHC -fno-warn-orphans #-}
+{-# LANGUAGE LambdaCase           #-}
+{-# LANGUAGE NoImplicitPrelude    #-}
+{- |
+   Module      : Text.Pandoc.Lua.Marshaling.CommonState
+   Copyright   : © 2012-2019 John MacFarlane
+                 © 2017-2019 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
+   Stability   : alpha
+
+Instances to marshal (push) and unmarshal (peek) the common state.
+-}
+module Text.Pandoc.Lua.Marshaling.CommonState () where
+
+import Prelude
+import Foreign.Lua (Lua, Peekable, Pushable)
+import Foreign.Lua.Types.Peekable (reportValueOnFailure)
+import Foreign.Lua.Userdata (ensureUserdataMetatable, pushAnyWithMetatable,
+                             toAnyWithName)
+import Text.Pandoc.Class (CommonState (..))
+import Text.Pandoc.Logging (LogMessage, showLogMessage)
+import Text.Pandoc.Lua.Marshaling.AnyValue (AnyValue (..))
+
+import qualified Data.Map as Map
+import qualified Foreign.Lua as Lua
+import qualified Text.Pandoc.Lua.Util as LuaUtil
+
+-- | Name used by Lua for the @CommonState@ type.
+commonStateTypeName :: String
+commonStateTypeName = "Pandoc CommonState"
+
+instance Peekable CommonState where
+  peek idx = reportValueOnFailure commonStateTypeName
+             (`toAnyWithName` commonStateTypeName) idx
+
+instance Pushable CommonState where
+  push st = pushAnyWithMetatable pushCommonStateMetatable st
+   where
+    pushCommonStateMetatable = ensureUserdataMetatable commonStateTypeName $ do
+      LuaUtil.addFunction "__index" indexCommonState
+      LuaUtil.addFunction "__pairs" pairsCommonState
+
+indexCommonState :: CommonState -> AnyValue -> Lua Lua.NumResults
+indexCommonState st (AnyValue idx) = Lua.ltype idx >>= \case
+  Lua.TypeString -> 1 <$ (Lua.peek idx >>= pushField)
+  _ -> 1 <$ Lua.pushnil
+ where
+  pushField :: String -> Lua ()
+  pushField name = case lookup name commonStateFields of
+    Just pushValue -> pushValue st
+    Nothing -> Lua.pushnil
+
+pairsCommonState :: CommonState -> Lua Lua.NumResults
+pairsCommonState st = do
+  Lua.pushHaskellFunction nextFn
+  Lua.pushnil
+  Lua.pushnil
+  return 3
+ where
+  nextFn :: AnyValue -> AnyValue -> Lua Lua.NumResults
+  nextFn _ (AnyValue idx) =
+    Lua.ltype idx >>= \case
+      Lua.TypeNil -> case commonStateFields of
+        []  -> 2 <$ (Lua.pushnil *> Lua.pushnil)
+        (key, pushValue):_ -> 2 <$ (Lua.push key *> pushValue st)
+      Lua.TypeString -> do
+        key <- Lua.peek idx
+        case tail $ dropWhile ((/= key) . fst) commonStateFields of
+          []                     -> 2 <$ (Lua.pushnil *> Lua.pushnil)
+          (nextKey, pushValue):_ -> 2 <$ (Lua.push nextKey *> pushValue st)
+      _ -> 2 <$ (Lua.pushnil *> Lua.pushnil)
+
+commonStateFields :: [(String, CommonState -> Lua ())]
+commonStateFields =
+  [ ("input_files", Lua.push . stInputFiles)
+  , ("output_file", Lua.push . Lua.Optional . stOutputFile)
+  , ("log", Lua.push . stLog)
+  , ("request_headers", Lua.push . Map.fromList . stRequestHeaders)
+  , ("resource_path", Lua.push . stResourcePath)
+  , ("source_url", Lua.push . Lua.Optional . stSourceURL)
+  , ("user_data_dir", Lua.push . Lua.Optional . stUserDataDir)
+  , ("trace", Lua.push . stTrace)
+  , ("verbosity", Lua.push . show . stVerbosity)
+  ]
+
+-- | Name used by Lua for the @CommonState@ type.
+logMessageTypeName :: String
+logMessageTypeName = "Pandoc LogMessage"
+
+instance Peekable LogMessage where
+  peek idx = reportValueOnFailure logMessageTypeName
+             (`toAnyWithName` logMessageTypeName) idx
+
+instance Pushable LogMessage where
+  push msg = pushAnyWithMetatable pushLogMessageMetatable msg
+   where
+    pushLogMessageMetatable = ensureUserdataMetatable logMessageTypeName $
+      LuaUtil.addFunction "__tostring" tostringLogMessage
+
+tostringLogMessage :: LogMessage -> Lua String
+tostringLogMessage = return . showLogMessage
diff --git a/src/Text/Pandoc/Lua/Marshaling/ReaderOptions.hs b/src/Text/Pandoc/Lua/Marshaling/ReaderOptions.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/Pandoc/Lua/Marshaling/ReaderOptions.hs
@@ -0,0 +1,79 @@
+{-# LANGUAGE NoImplicitPrelude    #-}
+{-# LANGUAGE FlexibleInstances    #-}
+{-# LANGUAGE ScopedTypeVariables  #-}
+{-# LANGUAGE LambdaCase           #-}
+{-# OPTIONS_GHC -fno-warn-orphans #-}
+{- |
+   Module      : Text.Pandoc.Lua.Marshaling.ReaderOptions
+   Copyright   : © 2012-2019 John MacFarlane
+                 © 2017-2019 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
+   Stability   : alpha
+
+Marshaling instance for ReaderOptions and its components.
+-}
+module Text.Pandoc.Lua.Marshaling.ReaderOptions () where
+
+import Prelude
+import Data.Data (showConstr, toConstr)
+import Foreign.Lua (Lua, Pushable)
+import Text.Pandoc.Extensions (Extensions)
+import Text.Pandoc.Lua.Marshaling.AnyValue (AnyValue (..))
+import Text.Pandoc.Lua.Marshaling.CommonState ()
+import Text.Pandoc.Options (ReaderOptions (..), TrackChanges)
+
+import qualified Data.Set as Set
+import qualified Foreign.Lua as Lua
+import qualified Text.Pandoc.Lua.Util as LuaUtil
+
+--
+-- Reader Options
+--
+instance Pushable Extensions where
+  push exts = Lua.push (show exts)
+
+instance Pushable TrackChanges where
+  push = Lua.push . showConstr . toConstr
+
+instance Pushable ReaderOptions where
+  push ro = do
+    let ReaderOptions
+          (extensions            :: Extensions)
+          (standalone            :: Bool)
+          (columns               :: Int)
+          (tabStop               :: Int)
+          (indentedCodeClasses   :: [String])
+          (abbreviations         :: Set.Set String)
+          (defaultImageExtension :: String)
+          (trackChanges          :: TrackChanges)
+          (stripComments         :: Bool)
+          = ro
+    Lua.newtable
+    LuaUtil.addField "extensions" extensions
+    LuaUtil.addField "standalone" standalone
+    LuaUtil.addField "columns" columns
+    LuaUtil.addField "tab_stop" tabStop
+    LuaUtil.addField "indented_code_classes" indentedCodeClasses
+    LuaUtil.addField "abbreviations" abbreviations
+    LuaUtil.addField "default_image_extension" defaultImageExtension
+    LuaUtil.addField "track_changes" trackChanges
+    LuaUtil.addField "strip_comments" stripComments
+
+    -- add metatable
+    let indexReaderOptions :: AnyValue -> AnyValue -> Lua Lua.NumResults
+        indexReaderOptions _tbl (AnyValue key) = do
+          Lua.ltype key >>= \case
+            Lua.TypeString -> Lua.peek key >>= \case
+              "defaultImageExtension" -> Lua.push defaultImageExtension
+              "indentedCodeClasses" -> Lua.push indentedCodeClasses
+              "stripComments" -> Lua.push stripComments
+              "tabStop" -> Lua.push tabStop
+              "trackChanges" -> Lua.push trackChanges
+              _ -> Lua.pushnil
+            _ -> Lua.pushnil
+          return 1
+    Lua.newtable
+    LuaUtil.addFunction "__index" indexReaderOptions
+    Lua.setmetatable (Lua.nthFromTop 2)
diff --git a/src/Text/Pandoc/Lua/Module/MediaBag.hs b/src/Text/Pandoc/Lua/Module/MediaBag.hs
--- a/src/Text/Pandoc/Lua/Module/MediaBag.hs
+++ b/src/Text/Pandoc/Lua/Module/MediaBag.hs
@@ -1,24 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright © 2017-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-
-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.Lua.Module.MediaBag
-   Copyright   : Copyright © 2017-2018 Albert Krewinkel
+   Copyright   : Copyright © 2017-2019 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
@@ -32,12 +15,11 @@
 
 import Prelude
 import Control.Monad (zipWithM_)
-import Data.IORef (IORef, modifyIORef', readIORef)
 import Data.Maybe (fromMaybe)
 import Foreign.Lua (Lua, NumResults, Optional, liftIO)
 import Text.Pandoc.Class (CommonState (..), fetchItem, putCommonState,
                           runIOorExplode, setMediaBag)
-import Text.Pandoc.Lua.StackInstances ()
+import Text.Pandoc.Lua.Marshaling ()
 import Text.Pandoc.Lua.Util (addFunction)
 import Text.Pandoc.MIME (MimeType)
 
@@ -48,30 +30,49 @@
 --
 -- MediaBag submodule
 --
-pushModule :: CommonState -> IORef MB.MediaBag -> Lua NumResults
-pushModule commonState mediaBagRef = do
+pushModule :: Lua NumResults
+pushModule = do
   Lua.newtable
-  addFunction "insert" (insertMediaFn mediaBagRef)
-  addFunction "lookup" (lookupMediaFn mediaBagRef)
-  addFunction "list" (mediaDirectoryFn mediaBagRef)
-  addFunction "fetch" (fetch commonState mediaBagRef)
+  addFunction "insert" insertMediaFn
+  addFunction "lookup" lookupMediaFn
+  addFunction "list" mediaDirectoryFn
+  addFunction "fetch" fetch
   return 1
 
-insertMediaFn :: IORef MB.MediaBag
-              -> FilePath
+--
+-- Port functions from Text.Pandoc.Class to the Lua monad.
+-- TODO: reuse existing functions.
+
+-- Get the current CommonState.
+getCommonState :: Lua CommonState
+getCommonState = do
+  Lua.getglobal "PANDOC_STATE"
+  Lua.peek Lua.stackTop
+
+-- Replace MediaBag in CommonState.
+setCommonState :: CommonState -> Lua ()
+setCommonState st = do
+  Lua.push st
+  Lua.setglobal "PANDOC_STATE"
+
+modifyCommonState :: (CommonState -> CommonState) -> Lua ()
+modifyCommonState f = getCommonState >>= setCommonState . f
+
+insertMediaFn :: FilePath
               -> Optional MimeType
               -> BL.ByteString
               -> Lua NumResults
-insertMediaFn mbRef fp optionalMime contents = do
-  liftIO . modifyIORef' mbRef $
-    MB.insertMedia fp (Lua.fromOptional optionalMime) contents
+insertMediaFn fp optionalMime contents = do
+  modifyCommonState $ \st ->
+    let mb = MB.insertMedia fp (Lua.fromOptional optionalMime) contents
+                               (stMediaBag st)
+    in st { stMediaBag = mb}
   return 0
 
-lookupMediaFn :: IORef MB.MediaBag
-              -> FilePath
+lookupMediaFn :: FilePath
               -> Lua NumResults
-lookupMediaFn mbRef fp = do
-  res <- MB.lookupMedia fp <$> liftIO (readIORef mbRef)
+lookupMediaFn fp = do
+  res <- MB.lookupMedia fp . stMediaBag <$> getCommonState
   case res of
     Nothing -> Lua.pushnil *> return 1
     Just (mimeType, contents) -> do
@@ -79,10 +80,9 @@
       Lua.push contents
       return 2
 
-mediaDirectoryFn :: IORef MB.MediaBag
-                 -> Lua NumResults
-mediaDirectoryFn mbRef = do
-  dirContents <- MB.mediaDirectory <$> liftIO (readIORef mbRef)
+mediaDirectoryFn :: Lua NumResults
+mediaDirectoryFn = do
+  dirContents <- MB.mediaDirectory . stMediaBag <$> getCommonState
   Lua.newtable
   zipWithM_ addEntry [1..] dirContents
   return 1
@@ -95,12 +95,11 @@
     Lua.push "length" *> Lua.push contentLength *> Lua.rawset (-3)
     Lua.rawseti (-2) idx
 
-fetch :: CommonState
-      -> IORef MB.MediaBag
-      -> String
+fetch :: String
       -> Lua NumResults
-fetch commonState mbRef src = do
-  mediaBag <- liftIO $ readIORef mbRef
+fetch src = do
+  commonState <- getCommonState
+  let mediaBag = stMediaBag commonState
   (bs, mimeType) <- liftIO . runIOorExplode $ do
     putCommonState commonState
     setMediaBag mediaBag
diff --git a/src/Text/Pandoc/Lua/Module/Pandoc.hs b/src/Text/Pandoc/Lua/Module/Pandoc.hs
--- a/src/Text/Pandoc/Lua/Module/Pandoc.hs
+++ b/src/Text/Pandoc/Lua/Module/Pandoc.hs
@@ -1,25 +1,8 @@
-{-
-Copyright © 2017-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-
-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
--}
 {-# LANGUAGE FlexibleContexts #-}
 {-# LANGUAGE NoImplicitPrelude #-}
 {- |
    Module      : Text.Pandoc.Lua.Module.Pandoc
-   Copyright   : Copyright © 2017-2018 Albert Krewinkel
+   Copyright   : Copyright © 2017-2019 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
@@ -41,7 +24,7 @@
 import Text.Pandoc.Class (runIO)
 import Text.Pandoc.Definition (Block, Inline)
 import Text.Pandoc.Lua.Filter (walkInlines, walkBlocks, LuaFilter)
-import Text.Pandoc.Lua.StackInstances ()
+import Text.Pandoc.Lua.Marshaling ()
 import Text.Pandoc.Walk (Walkable)
 import Text.Pandoc.Options (ReaderOptions (readerExtensions))
 import Text.Pandoc.Process (pipeProcess)
diff --git a/src/Text/Pandoc/Lua/Module/Utils.hs b/src/Text/Pandoc/Lua/Module/Utils.hs
--- a/src/Text/Pandoc/Lua/Module/Utils.hs
+++ b/src/Text/Pandoc/Lua/Module/Utils.hs
@@ -1,24 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright © 2017-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-
-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.Lua.Module.Utils
-   Copyright   : Copyright © 2017-2018 Albert Krewinkel
+   Copyright   : Copyright © 2017-2019 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
@@ -38,7 +21,7 @@
 import Text.Pandoc.Class (runIO, setUserDataDir)
 import Text.Pandoc.Definition ( Pandoc, Meta, MetaValue (..), Block, Inline
                               , Citation, Attr, ListAttributes)
-import Text.Pandoc.Lua.StackInstances ()
+import Text.Pandoc.Lua.Marshaling ()
 import Text.Pandoc.Lua.Util (addFunction)
 
 import qualified Data.Digest.Pure.SHA as SHA
diff --git a/src/Text/Pandoc/Lua/Packages.hs b/src/Text/Pandoc/Lua/Packages.hs
--- a/src/Text/Pandoc/Lua/Packages.hs
+++ b/src/Text/Pandoc/Lua/Packages.hs
@@ -1,26 +1,9 @@
-{-
-Copyright © 2017-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-
-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
--}
 {-# LANGUAGE FlexibleContexts #-}
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE ScopedTypeVariables #-}
 {- |
    Module      : Text.Pandoc.Lua.Packages
-   Copyright   : Copyright © 2017-2018 Albert Krewinkel
+   Copyright   : Copyright © 2017-2019 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
@@ -36,10 +19,8 @@
 import Prelude
 import Control.Monad (forM_)
 import Data.ByteString (ByteString)
-import Data.IORef (IORef)
 import Foreign.Lua (Lua, NumResults, liftIO)
-import Text.Pandoc.Class (CommonState, readDataFile, runIO, setUserDataDir)
-import Text.Pandoc.MediaBag (MediaBag)
+import Text.Pandoc.Class (readDataFile, runIO, setUserDataDir)
 
 import qualified Foreign.Lua as Lua
 import Text.Pandoc.Lua.Module.Pandoc as Pandoc
@@ -48,9 +29,7 @@
 
 -- | Parameters used to create lua packages/modules.
 data LuaPackageParams = LuaPackageParams
-  { luaPkgCommonState :: CommonState
-  , luaPkgDataDir :: Maybe FilePath
-  , luaPkgMediaBag :: IORef MediaBag
+  { luaPkgDataDir :: Maybe FilePath
   }
 
 -- | Insert pandoc's package loader as the first loader, making it the default.
@@ -68,15 +47,13 @@
 
 -- | Load a pandoc module.
 pandocPackageSearcher :: LuaPackageParams -> String -> Lua NumResults
-pandocPackageSearcher luaPkgParams pkgName =
+pandocPackageSearcher pkgParams pkgName =
   case pkgName of
-    "pandoc"          -> let datadir = luaPkgDataDir luaPkgParams
+    "pandoc"          -> let datadir = luaPkgDataDir pkgParams
                          in pushWrappedHsFun (Pandoc.pushModule datadir)
-    "pandoc.mediabag" -> let st    = luaPkgCommonState luaPkgParams
-                             mbRef = luaPkgMediaBag luaPkgParams
-                         in pushWrappedHsFun (MediaBag.pushModule st mbRef)
-    "pandoc.utils"    -> let datadirMb = luaPkgDataDir luaPkgParams
-                         in pushWrappedHsFun (Utils.pushModule datadirMb)
+    "pandoc.mediabag" -> pushWrappedHsFun MediaBag.pushModule
+    "pandoc.utils"    -> let datadir = luaPkgDataDir pkgParams
+                         in pushWrappedHsFun (Utils.pushModule datadir)
     _ -> searchPureLuaLoader
  where
   pushWrappedHsFun f = do
@@ -84,11 +61,11 @@
     return 1
   searchPureLuaLoader = do
     let filename = pkgName ++ ".lua"
-    modScript <- liftIO (dataDirScript (luaPkgDataDir luaPkgParams) filename)
+    modScript <- liftIO (dataDirScript (luaPkgDataDir pkgParams) filename)
     case modScript of
       Just script -> pushWrappedHsFun (loadStringAsPackage pkgName script)
       Nothing -> do
-        Lua.push ("no file '" ++ filename ++ "' in pandoc's datadir")
+        Lua.push ("\n\tno file '" ++ filename ++ "' in pandoc's datadir")
         return 1
 
 loadStringAsPackage :: String -> ByteString -> Lua NumResults
diff --git a/src/Text/Pandoc/Lua/StackInstances.hs b/src/Text/Pandoc/Lua/StackInstances.hs
deleted file mode 100644
--- a/src/Text/Pandoc/Lua/StackInstances.hs
+++ /dev/null
@@ -1,474 +0,0 @@
-{-# LANGUAGE NoImplicitPrelude    #-}
-{-# LANGUAGE FlexibleInstances    #-}
-{-# LANGUAGE ScopedTypeVariables  #-}
-{-# LANGUAGE LambdaCase           #-}
-{-# OPTIONS_GHC -fno-warn-orphans #-}
-{-
-Copyright © 2012-2018 John MacFarlane <jgm@berkeley.edu>
-            2017-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-
-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.Lua.StackInstances
-   Copyright   : © 2012-2018 John MacFarlane
-                 © 2017-2018 Albert Krewinkel
-   License     : GNU GPL, version 2 or above
-
-   Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-   Stability   : alpha
-
-StackValue instances for pandoc types.
--}
-module Text.Pandoc.Lua.StackInstances () where
-
-import Prelude
-import Control.Applicative ((<|>))
-import Data.Data (showConstr, toConstr)
-import Foreign.Lua (Lua, Peekable, Pushable, StackIndex)
-import Foreign.Lua.Types.Peekable (reportValueOnFailure)
-import Foreign.Lua.Userdata ( ensureUserdataMetatable, pushAnyWithMetatable
-                            , toAnyWithName, metatableName)
-import Text.Pandoc.Class (CommonState (..))
-import Text.Pandoc.Definition
-import Text.Pandoc.Extensions (Extensions)
-import Text.Pandoc.Logging (LogMessage, showLogMessage)
-import Text.Pandoc.Lua.Util (defineHowTo, pushViaConstructor)
-import Text.Pandoc.Options (ReaderOptions (..), TrackChanges)
-import Text.Pandoc.Shared (Element (Blk, Sec))
-
-import qualified Data.Map as Map
-import qualified Data.Set as Set
-import qualified Foreign.Lua as Lua
-import qualified Text.Pandoc.Lua.Util as LuaUtil
-
-instance Pushable Pandoc where
-  push (Pandoc meta blocks) =
-    pushViaConstructor "Pandoc" blocks meta
-
-instance Peekable Pandoc where
-  peek idx = defineHowTo "get Pandoc value" $ do
-    blocks <- LuaUtil.rawField idx "blocks"
-    meta   <- LuaUtil.rawField idx "meta"
-    return $ Pandoc meta blocks
-
-instance Pushable Meta where
-  push (Meta mmap) =
-    pushViaConstructor "Meta" mmap
-instance Peekable Meta where
-  peek idx = defineHowTo "get Meta value" $
-    Meta <$> Lua.peek idx
-
-instance Pushable MetaValue where
-  push = pushMetaValue
-instance Peekable MetaValue where
-  peek = peekMetaValue
-
-instance Pushable Block where
-  push = pushBlock
-
-instance Peekable Block where
-  peek = peekBlock
-
--- Inline
-instance Pushable Inline where
-  push = pushInline
-
-instance Peekable Inline where
-  peek = peekInline
-
--- Citation
-instance Pushable Citation where
-  push (Citation cid prefix suffix mode noteNum hash) =
-    pushViaConstructor "Citation" cid mode prefix suffix noteNum hash
-
-instance Peekable Citation where
-  peek idx = do
-    id' <- LuaUtil.rawField idx "id"
-    prefix <- LuaUtil.rawField idx "prefix"
-    suffix <- LuaUtil.rawField idx "suffix"
-    mode <- LuaUtil.rawField idx "mode"
-    num <- LuaUtil.rawField idx "note_num"
-    hash <- LuaUtil.rawField idx "hash"
-    return $ Citation id' prefix suffix mode num hash
-
-instance Pushable Alignment where
-  push = Lua.push . show
-instance Peekable Alignment where
-  peek = Lua.peekRead
-
-instance Pushable CitationMode where
-  push = Lua.push . show
-instance Peekable CitationMode where
-  peek = Lua.peekRead
-
-instance Pushable Format where
-  push (Format f) = Lua.push f
-instance Peekable Format where
-  peek idx = Format <$> Lua.peek idx
-
-instance Pushable ListNumberDelim where
-  push = Lua.push . show
-instance Peekable ListNumberDelim where
-  peek = Lua.peekRead
-
-instance Pushable ListNumberStyle where
-  push = Lua.push . show
-instance Peekable ListNumberStyle where
-  peek = Lua.peekRead
-
-instance Pushable MathType where
-  push = Lua.push . show
-instance Peekable MathType where
-  peek = Lua.peekRead
-
-instance Pushable QuoteType where
-  push = Lua.push . show
-instance Peekable QuoteType where
-  peek = Lua.peekRead
-
--- | Push an meta value element to the top of the lua stack.
-pushMetaValue :: MetaValue -> Lua ()
-pushMetaValue = \case
-  MetaBlocks blcks  -> pushViaConstructor "MetaBlocks" blcks
-  MetaBool bool     -> Lua.push bool
-  MetaInlines inlns -> pushViaConstructor "MetaInlines" inlns
-  MetaList metalist -> pushViaConstructor "MetaList" metalist
-  MetaMap metamap   -> pushViaConstructor "MetaMap" metamap
-  MetaString str    -> Lua.push str
-
--- | Interpret the value at the given stack index as meta value.
-peekMetaValue :: StackIndex -> Lua MetaValue
-peekMetaValue idx = defineHowTo "get MetaValue" $ do
-  -- Get the contents of an AST element.
-  let elementContent :: Peekable a => Lua a
-      elementContent = Lua.peek idx
-  luatype <- Lua.ltype idx
-  case luatype of
-    Lua.TypeBoolean -> MetaBool <$> Lua.peek idx
-    Lua.TypeString  -> MetaString <$> Lua.peek idx
-    Lua.TypeTable   -> do
-      tag <- Lua.try $ LuaUtil.getTag idx
-      case tag of
-        Right "MetaBlocks"  -> MetaBlocks  <$> elementContent
-        Right "MetaBool"    -> MetaBool    <$> elementContent
-        Right "MetaMap"     -> MetaMap     <$> elementContent
-        Right "MetaInlines" -> MetaInlines <$> elementContent
-        Right "MetaList"    -> MetaList    <$> elementContent
-        Right "MetaString"  -> MetaString  <$> elementContent
-        Right t             -> Lua.throwException ("Unknown meta tag: " <> t)
-        Left _ -> do
-          -- no meta value tag given, try to guess.
-          len <- Lua.rawlen idx
-          if len <= 0
-            then MetaMap <$> Lua.peek idx
-            else  (MetaInlines <$> Lua.peek idx)
-                  <|> (MetaBlocks <$> Lua.peek idx)
-                  <|> (MetaList <$> Lua.peek idx)
-    _        -> Lua.throwException "could not get meta value"
-
--- | Push an block element to the top of the lua stack.
-pushBlock :: Block -> Lua ()
-pushBlock = \case
-  BlockQuote blcks         -> pushViaConstructor "BlockQuote" blcks
-  BulletList items         -> pushViaConstructor "BulletList" items
-  CodeBlock attr code      -> pushViaConstructor "CodeBlock" code (LuaAttr attr)
-  DefinitionList items     -> pushViaConstructor "DefinitionList" items
-  Div attr blcks           -> pushViaConstructor "Div" blcks (LuaAttr attr)
-  Header lvl attr inlns    -> pushViaConstructor "Header" lvl inlns (LuaAttr attr)
-  HorizontalRule           -> pushViaConstructor "HorizontalRule"
-  LineBlock blcks          -> pushViaConstructor "LineBlock" blcks
-  OrderedList lstAttr list -> pushViaConstructor "OrderedList" list
-                                                 (LuaListAttributes lstAttr)
-  Null                     -> pushViaConstructor "Null"
-  Para blcks               -> pushViaConstructor "Para" blcks
-  Plain blcks              -> pushViaConstructor "Plain" blcks
-  RawBlock f cs            -> pushViaConstructor "RawBlock" f cs
-  Table capt aligns widths headers rows ->
-    pushViaConstructor "Table" capt aligns widths headers rows
-
--- | Return the value at the given index as block if possible.
-peekBlock :: StackIndex -> Lua Block
-peekBlock idx = defineHowTo "get Block value" $ do
-  tag <- LuaUtil.getTag idx
-  case tag of
-      "BlockQuote"     -> BlockQuote <$> elementContent
-      "BulletList"     -> BulletList <$> elementContent
-      "CodeBlock"      -> withAttr CodeBlock <$> elementContent
-      "DefinitionList" -> DefinitionList <$> elementContent
-      "Div"            -> withAttr Div <$> elementContent
-      "Header"         -> (\(lvl, LuaAttr attr, lst) -> Header lvl attr lst)
-                          <$> elementContent
-      "HorizontalRule" -> return HorizontalRule
-      "LineBlock"      -> LineBlock <$> elementContent
-      "OrderedList"    -> (\(LuaListAttributes lstAttr, lst) ->
-                             OrderedList lstAttr lst)
-                          <$> elementContent
-      "Null"           -> return Null
-      "Para"           -> Para <$> elementContent
-      "Plain"          -> Plain <$> elementContent
-      "RawBlock"       -> uncurry RawBlock <$> elementContent
-      "Table"          -> (\(capt, aligns, widths, headers, body) ->
-                                  Table capt aligns widths headers body)
-                          <$> elementContent
-      _ -> Lua.throwException ("Unknown block type: " <> tag)
- where
-   -- Get the contents of an AST element.
-   elementContent :: Peekable a => Lua a
-   elementContent = LuaUtil.rawField idx "c"
-
--- | Push an inline element to the top of the lua stack.
-pushInline :: Inline -> Lua ()
-pushInline = \case
-  Cite citations lst       -> pushViaConstructor "Cite" lst citations
-  Code attr lst            -> pushViaConstructor "Code" lst (LuaAttr attr)
-  Emph inlns               -> pushViaConstructor "Emph" inlns
-  Image attr alt (src,tit) -> pushViaConstructor "Image" alt src tit (LuaAttr attr)
-  LineBreak                -> pushViaConstructor "LineBreak"
-  Link attr lst (src,tit)  -> pushViaConstructor "Link" lst src tit (LuaAttr attr)
-  Note blcks               -> pushViaConstructor "Note" blcks
-  Math mty str             -> pushViaConstructor "Math" mty str
-  Quoted qt inlns          -> pushViaConstructor "Quoted" qt inlns
-  RawInline f cs           -> pushViaConstructor "RawInline" f cs
-  SmallCaps inlns          -> pushViaConstructor "SmallCaps" inlns
-  SoftBreak                -> pushViaConstructor "SoftBreak"
-  Space                    -> pushViaConstructor "Space"
-  Span attr inlns          -> pushViaConstructor "Span" inlns (LuaAttr attr)
-  Str str                  -> pushViaConstructor "Str" str
-  Strikeout inlns          -> pushViaConstructor "Strikeout" inlns
-  Strong inlns             -> pushViaConstructor "Strong" inlns
-  Subscript inlns          -> pushViaConstructor "Subscript" inlns
-  Superscript inlns        -> pushViaConstructor "Superscript" inlns
-
--- | Return the value at the given index as inline if possible.
-peekInline :: StackIndex -> Lua Inline
-peekInline idx = defineHowTo "get Inline value" $ do
-  tag <- LuaUtil.getTag idx
-  case tag of
-    "Cite"       -> uncurry Cite <$> elementContent
-    "Code"       -> withAttr Code <$> elementContent
-    "Emph"       -> Emph <$> elementContent
-    "Image"      -> (\(LuaAttr attr, lst, tgt) -> Image attr lst tgt)
-                    <$> elementContent
-    "Link"       -> (\(LuaAttr attr, lst, tgt) -> Link attr lst tgt)
-                    <$> elementContent
-    "LineBreak"  -> return LineBreak
-    "Note"       -> Note <$> elementContent
-    "Math"       -> uncurry Math <$> elementContent
-    "Quoted"     -> uncurry Quoted <$> elementContent
-    "RawInline"  -> uncurry RawInline <$> elementContent
-    "SmallCaps"  -> SmallCaps <$> elementContent
-    "SoftBreak"  -> return SoftBreak
-    "Space"      -> return Space
-    "Span"       -> withAttr Span <$> elementContent
-    "Str"        -> Str <$> elementContent
-    "Strikeout"  -> Strikeout <$> elementContent
-    "Strong"     -> Strong <$> elementContent
-    "Subscript"  -> Subscript <$> elementContent
-    "Superscript"-> Superscript <$> elementContent
-    _ -> Lua.throwException ("Unknown inline type: " <> tag)
- where
-   -- Get the contents of an AST element.
-   elementContent :: Peekable a => Lua a
-   elementContent = LuaUtil.rawField idx "c"
-
-withAttr :: (Attr -> a -> b) -> (LuaAttr, a) -> b
-withAttr f (attributes, x) = f (fromLuaAttr attributes) x
-
--- | Wrapper for Attr
-newtype LuaAttr = LuaAttr { fromLuaAttr :: Attr }
-
-instance Pushable LuaAttr where
-  push (LuaAttr (id', classes, kv)) =
-    pushViaConstructor "Attr" id' classes kv
-
-instance Peekable LuaAttr where
-  peek idx = defineHowTo "get Attr value" (LuaAttr <$> Lua.peek idx)
-
--- | Wrapper for ListAttributes
-newtype LuaListAttributes = LuaListAttributes  ListAttributes
-
-instance Pushable LuaListAttributes where
-  push (LuaListAttributes (start, style, delimiter)) =
-    pushViaConstructor "ListAttributes" start style delimiter
-
-instance Peekable LuaListAttributes where
-  peek = defineHowTo "get ListAttributes value" .
-         fmap LuaListAttributes . Lua.peek
-
---
--- Hierarchical elements
---
-instance Pushable Element where
-  push (Blk blk) = Lua.push blk
-  push sec = pushAnyWithMetatable pushElementMetatable sec
-   where
-    pushElementMetatable = ensureUserdataMetatable (metatableName sec) $
-                           LuaUtil.addFunction "__index" indexElement
-
-instance Peekable Element where
-  peek idx = Lua.ltype idx >>= \case
-    Lua.TypeUserdata -> Lua.peekAny idx
-    _                -> Blk <$> Lua.peek idx
-
-indexElement :: Element -> String -> Lua Lua.NumResults
-indexElement = \case
-  (Blk _) -> const (1 <$ Lua.pushnil) -- this shouldn't happen
-  (Sec lvl num attr label contents) -> fmap (return 1) . \case
-    "level"     -> Lua.push lvl
-    "numbering" -> Lua.push num
-    "attr"      -> Lua.push (LuaAttr attr)
-    "label"     -> Lua.push label
-    "contents"  -> Lua.push contents
-    "tag"       -> Lua.push "Sec"
-    "t"         -> Lua.push "Sec"
-    _           -> Lua.pushnil
-
-
---
--- Reader Options
---
-instance Pushable Extensions where
-  push exts = Lua.push (show exts)
-
-instance Pushable TrackChanges where
-  push = Lua.push . showConstr . toConstr
-
-instance Pushable ReaderOptions where
-  push ro = do
-    let ReaderOptions
-          (extensions            :: Extensions)
-          (standalone            :: Bool)
-          (columns               :: Int)
-          (tabStop               :: Int)
-          (indentedCodeClasses   :: [String])
-          (abbreviations         :: Set.Set String)
-          (defaultImageExtension :: String)
-          (trackChanges          :: TrackChanges)
-          (stripComments         :: Bool)
-          = ro
-    Lua.newtable
-    LuaUtil.addField "extensions" extensions
-    LuaUtil.addField "standalone" standalone
-    LuaUtil.addField "columns" columns
-    LuaUtil.addField "tab_stop" tabStop
-    LuaUtil.addField "indented_code_classes" indentedCodeClasses
-    LuaUtil.addField "abbreviations" abbreviations
-    LuaUtil.addField "default_image_extension" defaultImageExtension
-    LuaUtil.addField "track_changes" trackChanges
-    LuaUtil.addField "strip_comments" stripComments
-
-    -- add metatable
-    let indexReaderOptions :: AnyValue -> AnyValue -> Lua Lua.NumResults
-        indexReaderOptions _tbl (AnyValue key) = do
-          Lua.ltype key >>= \case
-            Lua.TypeString -> Lua.peek key >>= \case
-              "defaultImageExtension" -> Lua.push defaultImageExtension
-              "indentedCodeClasses" -> Lua.push indentedCodeClasses
-              "stripComments" -> Lua.push stripComments
-              "tabStop" -> Lua.push tabStop
-              "trackChanges" -> Lua.push trackChanges
-              _ -> Lua.pushnil
-            _ -> Lua.pushnil
-          return 1
-    Lua.newtable
-    LuaUtil.addFunction "__index" indexReaderOptions
-    Lua.setmetatable (Lua.nthFromTop 2)
-
--- | Dummy type to allow values of arbitrary Lua type.
-newtype AnyValue = AnyValue StackIndex
-
---
--- TODO: Much of the following should be abstracted, factored out
--- and go into HsLua.
---
-
-instance Peekable AnyValue where
-  peek = return . AnyValue
-
--- | Name used by Lua for the @CommonState@ type.
-commonStateTypeName :: String
-commonStateTypeName = "Pandoc CommonState"
-
-instance Peekable CommonState where
-  peek idx = reportValueOnFailure commonStateTypeName
-             (`toAnyWithName` commonStateTypeName) idx
-
-instance Pushable CommonState where
-  push st = pushAnyWithMetatable pushCommonStateMetatable st
-   where
-    pushCommonStateMetatable = ensureUserdataMetatable commonStateTypeName $ do
-      LuaUtil.addFunction "__index" indexCommonState
-      LuaUtil.addFunction "__pairs" pairsCommonState
-
-indexCommonState :: CommonState -> AnyValue -> Lua Lua.NumResults
-indexCommonState st (AnyValue idx) = Lua.ltype idx >>= \case
-  Lua.TypeString -> 1 <$ (Lua.peek idx >>= pushField)
-  _ -> 1 <$ Lua.pushnil
- where
-  pushField :: String -> Lua ()
-  pushField name = case lookup name commonStateFields of
-    Just pushValue -> pushValue st
-    Nothing -> Lua.pushnil
-
-pairsCommonState :: CommonState -> Lua Lua.NumResults
-pairsCommonState st = do
-  Lua.pushHaskellFunction nextFn
-  Lua.pushnil
-  Lua.pushnil
-  return 3
- where
-  nextFn :: AnyValue -> AnyValue -> Lua Lua.NumResults
-  nextFn _ (AnyValue idx) =
-    Lua.ltype idx >>= \case
-      Lua.TypeNil -> case commonStateFields of
-        []  -> 2 <$ (Lua.pushnil *> Lua.pushnil)
-        (key, pushValue):_ -> 2 <$ (Lua.push key *> pushValue st)
-      Lua.TypeString -> do
-        key <- Lua.peek idx
-        case tail $ dropWhile ((/= key) . fst) commonStateFields of
-          []                     -> 2 <$ (Lua.pushnil *> Lua.pushnil)
-          (nextKey, pushValue):_ -> 2 <$ (Lua.push nextKey *> pushValue st)
-      _ -> 2 <$ (Lua.pushnil *> Lua.pushnil)
-
-commonStateFields :: [(String, CommonState -> Lua ())]
-commonStateFields =
-  [ ("input_files", Lua.push . stInputFiles)
-  , ("output_file", Lua.push . Lua.Optional . stOutputFile)
-  , ("log", Lua.push . stLog)
-  , ("request_headers", Lua.push . Map.fromList . stRequestHeaders)
-  , ("resource_path", Lua.push . stResourcePath)
-  , ("source_url", Lua.push . Lua.Optional . stSourceURL)
-  , ("user_data_dir", Lua.push . Lua.Optional . stUserDataDir)
-  , ("trace", Lua.push . stTrace)
-  , ("verbosity", Lua.push . show . stVerbosity)
-  ]
-
--- | Name used by Lua for the @CommonState@ type.
-logMessageTypeName :: String
-logMessageTypeName = "Pandoc LogMessage"
-
-instance Peekable LogMessage where
-  peek idx = reportValueOnFailure logMessageTypeName
-             (`toAnyWithName` logMessageTypeName) idx
-
-instance Pushable LogMessage where
-  push msg = pushAnyWithMetatable pushLogMessageMetatable msg
-   where
-    pushLogMessageMetatable = ensureUserdataMetatable logMessageTypeName $
-      LuaUtil.addFunction "__tostring" tostringLogMessage
-
-tostringLogMessage :: LogMessage -> Lua String
-tostringLogMessage = return . showLogMessage
diff --git a/src/Text/Pandoc/Lua/Util.hs b/src/Text/Pandoc/Lua/Util.hs
--- a/src/Text/Pandoc/Lua/Util.hs
+++ b/src/Text/Pandoc/Lua/Util.hs
@@ -1,28 +1,10 @@
-{-
-Copyright © 2012-2018 John MacFarlane <jgm@berkeley.edu>
-            2017-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-
-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
--}
 {-# LANGUAGE FlexibleInstances #-}
 {-# LANGUAGE LambdaCase #-}
 {-# LANGUAGE NoImplicitPrelude #-}
 {- |
    Module      : Text.Pandoc.Lua.Util
-   Copyright   : © 2012–2018 John MacFarlane,
-                 © 2017-2018 Albert Krewinkel
+   Copyright   : © 2012–2019 John MacFarlane,
+                 © 2017-2019 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
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
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2011-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.MIME
-   Copyright   : Copyright (C) 2011-2018 John MacFarlane
+   Copyright   : Copyright (C) 2011-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -490,6 +472,7 @@
            ,("wbmp","image/vnd.wap.wbmp")
            ,("wbxml","application/vnd.wap.wbxml")
            ,("webm","video/webm")
+           ,("webp","image/webp")
            ,("wk","application/x-123")
            ,("wm","video/x-ms-wm")
            ,("wma","audio/x-ms-wma")
diff --git a/src/Text/Pandoc/MediaBag.hs b/src/Text/Pandoc/MediaBag.hs
--- a/src/Text/Pandoc/MediaBag.hs
+++ b/src/Text/Pandoc/MediaBag.hs
@@ -2,27 +2,9 @@
 {-# LANGUAGE CPP                        #-}
 {-# LANGUAGE DeriveDataTypeable         #-}
 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
-{-
-Copyright (C) 2014-2015, 2017–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.MediaBag
-   Copyright   : Copyright (C) 2014-2015, 2017–2018 John MacFarlane
+   Copyright   : Copyright (C) 2014-2015, 2017–2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
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
@@ -5,28 +5,9 @@
 #ifdef DERIVE_JSON_VIA_TH
 {-# LANGUAGE TemplateHaskell    #-}
 #endif
-
-{-
-Copyright (C) 2012-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.Options
-   Copyright   : Copyright (C) 2012-2018 John MacFarlane
+   Copyright   : Copyright (C) 2012-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -181,7 +162,7 @@
   , writerSectionDivs       :: Bool   -- ^ Put sections in div tags in HTML
   , writerExtensions        :: Extensions -- ^ Markdown extensions that can be used
   , writerReferenceLinks    :: Bool   -- ^ Use reference links in writing markdown, rst
-  , writerDpi               :: Int    -- ^ Dpi for pixel to/from inch/cm conversions
+  , writerDpi               :: Int    -- ^ Dpi for pixel to\/from inch\/cm conversions
   , writerWrapText          :: WrapOption  -- ^ Option for wrapping text
   , writerColumns           :: Int    -- ^ Characters in a line (for text wrapping)
   , writerEmailObfuscation  :: ObfuscationMethod -- ^ How to obfuscate emails
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
@@ -2,27 +2,9 @@
 {-# LANGUAGE CPP                 #-}
 {-# LANGUAGE OverloadedStrings   #-}
 {-# LANGUAGE ScopedTypeVariables #-}
-{-
-Copyright (C) 2012-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.PDF
-   Copyright   : Copyright (C) 2012-2018 John MacFarlane
+   Copyright   : Copyright (C) 2012-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -50,7 +32,8 @@
 import System.Exit (ExitCode (..))
 import System.FilePath
 import System.IO (stdout)
-import System.IO.Temp (withTempDirectory, withTempFile)
+import System.IO.Temp (withSystemTempDirectory, withTempDirectory,
+                       withTempFile)
 #if MIN_VERSION_base(4,8,3)
 import System.IO.Error (IOError, isDoesNotExistError)
 #else
@@ -68,8 +51,9 @@
 #ifdef _WINDOWS
 import Data.List (intercalate)
 #endif
+import Data.List (isPrefixOf)
 import Text.Pandoc.Class (PandocIO, extractMedia, fillMediaBag, getCommonState,
-                          getVerbosity, putCommonState, report, runIO,
+                          getVerbosity, putCommonState, report,
                           runIOorExplode, setVerbosity)
 import Text.Pandoc.Logging
 
@@ -98,25 +82,39 @@
       let args   = ["-ms", "-mpdfmark", "-e", "-t", "-k", "-KUTF-8", "-i",
                     "--no-toc-relocation"] ++ pdfargs
       verbosity <- getVerbosity
-      liftIO $ ms2pdf verbosity program args source
+      liftIO $ generic2pdf verbosity program args source
     baseProg -> do
-      -- 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
-        source <- runIOorExplode $ do
-                    putCommonState commonState
-                    doc' <- handleImages tmpdir doc
-                    writer opts doc'
-        case baseProg of
-           "context" -> context2pdf verbosity program tmpdir source
-           prog | prog `elem` ["pdflatex", "lualatex", "xelatex"]
-               -> tex2pdf verbosity program pdfargs tmpdir source
-           _ -> return $ Left $ UTF8.fromStringLazy $ "Unknown program " ++ program
+      -- latex has trouble with tildes in paths, which
+      -- you find in Windows temp dir paths with longer
+      -- user names (see #777)
+      let withTempDir templ action = do
+            tmp <- getTemporaryDirectory
+            if '~' `elem` tmp
+                   then withTempDirectory "." templ action
+                   else withSystemTempDirectory templ action
+      (newCommonState, res) <- liftIO $ withTempDir "tex2pdf." $ \tmpdir' -> do
+#ifdef _WINDOWS
+        -- note:  we want / even on Windows, for TexLive
+        let tmpdir = changePathSeparators tmpdir'
+#else
+        let tmpdir = tmpdir'
+#endif
+        runIOorExplode $ do
+          putCommonState commonState
+          doc' <- handleImages tmpdir doc
+          source <- writer opts doc'
+          res <- case baseProg of
+            "context" -> context2pdf verbosity program pdfargs tmpdir source
+            prog | prog `elem` ["pdflatex", "lualatex", "xelatex", "latexmk"]
+                -> tex2pdf verbosity program pdfargs tmpdir source
+            _ -> return $ Left $ UTF8.fromStringLazy
+                               $ "Unknown program " ++ program
+          cs <- getCommonState
+          return (cs, res)
+      putCommonState newCommonState
+      return res
 
 makeWithWkhtmltopdf :: String              -- ^ wkhtmltopdf or path
                     -> [String]            -- ^ arguments
@@ -207,17 +205,16 @@
         -> [String]                        -- ^ Arguments to the latex-engine
         -> FilePath                        -- ^ temp directory for output
         -> Text                            -- ^ tex source
-        -> IO (Either ByteString ByteString)
+        -> PandocIO (Either ByteString ByteString)
 tex2pdf verbosity program args tmpDir source = do
-  let numruns = if "\\tableofcontents" `T.isInfixOf` source
+  let numruns =
+        if takeBaseName program == "latexmk"
+           then 1
+           else if "\\tableofcontents" `T.isInfixOf` source
                    then 3  -- to get page numbers
                    else 2  -- 1 run won't give you PDF bookmarks
-  (exit, log', mbPdf) <- E.catch
-    (runTeXProgram verbosity program args 1 numruns tmpDir source)
-    (\(e :: IOError) -> if isDoesNotExistError e
-                           then E.throwIO $
-                                 PandocPDFProgramNotFoundError program
-                           else E.throwIO e)
+  (exit, log', mbPdf) <- runTeXProgram verbosity program args 1 numruns
+                          tmpDir source
   case (exit, mbPdf) of
        (ExitFailure _, _)      -> do
           let logmsg = extractMsg log'
@@ -233,7 +230,7 @@
           missingCharacterWarnings verbosity log'
           return $ Right pdf
 
-missingCharacterWarnings :: Verbosity -> ByteString -> IO ()
+missingCharacterWarnings :: Verbosity -> ByteString -> PandocIO ()
 missingCharacterWarnings verbosity log' = do
   let ls = BC.lines log'
   let isMissingCharacterWarning = BC.isPrefixOf "Missing character: "
@@ -241,10 +238,8 @@
                  | l <- ls
                  , isMissingCharacterWarning l
                  ]
-  runIO $ do
-    setVerbosity verbosity
-    mapM_ (report . MissingCharacter) warnings
-  return ()
+  setVerbosity verbosity
+  mapM_ (report . MissingCharacter) warnings
 
 -- parsing output
 
@@ -271,41 +266,40 @@
 -- contents of stdout, contents of produced PDF if any).  Rerun
 -- a fixed number of times to resolve references.
 runTeXProgram :: Verbosity -> String -> [String] -> Int -> Int -> FilePath
-              -> Text -> IO (ExitCode, ByteString, Maybe ByteString)
-runTeXProgram verbosity program args runNumber numRuns tmpDir source = do
+              -> Text -> PandocIO (ExitCode, ByteString, Maybe ByteString)
+runTeXProgram verbosity program args runNumber numRuns tmpDir' source = do
+    let tmpDir =
+          case [x | x <- args, "-outdir=" `isPrefixOf` x] of
+            [x] -> drop 8 x
+            _   -> tmpDir'
+    liftIO $ createDirectoryIfMissing True tmpDir
     let file = tmpDir </> "input.tex"
-    exists <- doesFileExist file
-    unless exists $ BS.writeFile file $ UTF8.fromText source
-#ifdef _WINDOWS
-    -- note:  we want / even on Windows, for TexLive
-    let tmpDir' = changePathSeparators tmpDir
-    let file' = changePathSeparators file
-#else
-    let tmpDir' = tmpDir
-    let file' = file
-#endif
-    let programArgs = ["-halt-on-error", "-interaction", "nonstopmode",
-         "-output-directory", tmpDir'] ++ args ++ [file']
-    env' <- getEnvironment
+    exists <- liftIO $ doesFileExist file
+    unless exists $ liftIO $ BS.writeFile file $ UTF8.fromText source
+    let programArgs =
+          if takeBaseName program == "latexmk"
+             then ["-interaction=batchmode", "-halt-on-error", "-pdf",
+                   "-quiet", "-outdir=" ++ tmpDir] ++ args ++ [file]
+             else ["-halt-on-error", "-interaction", "nonstopmode",
+                   "-output-directory", tmpDir] ++ args ++ [file]
+    env' <- liftIO getEnvironment
     let sep = [searchPathSeparator]
-    let texinputs = maybe (tmpDir' ++ sep) ((tmpDir' ++ sep) ++)
+    let texinputs = maybe (tmpDir ++ sep) ((tmpDir ++ sep) ++)
           $ lookup "TEXINPUTS" env'
     let env'' = ("TEXINPUTS", texinputs) :
-                  [(k,v) | (k,v) <- env', k /= "TEXINPUTS"]
-    when (verbosity >= INFO && runNumber == 1) $ do
-      putStrLn "[makePDF] temp dir:"
-      putStrLn tmpDir'
-      putStrLn "[makePDF] Command line:"
-      putStrLn $ program ++ " " ++ unwords (map show programArgs)
-      putStr "\n"
-      putStrLn "[makePDF] Environment:"
-      mapM_ print env''
-      putStr "\n"
-      putStrLn $ "[makePDF] Contents of " ++ file' ++ ":"
-      BL.readFile file' >>= BL.putStr
-      putStr "\n"
-    (exit, out) <- pipeProcess (Just env'') program programArgs BL.empty
-    when (verbosity >= INFO) $ do
+                ("TEXMFOUTPUT", tmpDir) :
+                  [(k,v) | (k,v) <- env'
+                         , k /= "TEXINPUTS" && k /= "TEXMFOUTPUT"]
+    when (runNumber == 1 && verbosity >= INFO) $ liftIO $
+      UTF8.readFile file >>=
+       showVerboseInfo (Just tmpDir) program programArgs env''
+    (exit, out) <- liftIO $ E.catch
+      (pipeProcess (Just env'') program programArgs BL.empty)
+      (\(e :: IOError) -> if isDoesNotExistError e
+                             then E.throwIO $ PandocPDFProgramNotFoundError
+                                   program
+                             else E.throwIO e)
+    when (verbosity >= INFO) $ liftIO $ do
       putStrLn $ "[makePDF] Run #" ++ show runNumber
       BL.hPutStr stdout out
       putStr "\n"
@@ -313,39 +307,32 @@
        then runTeXProgram verbosity program args (runNumber + 1) numRuns tmpDir source
        else do
          let pdfFile = replaceDirectory (replaceExtension file ".pdf") tmpDir
-         pdfExists <- doesFileExist pdfFile
+         pdfExists <- liftIO $ doesFileExist pdfFile
          pdf <- 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 (Just . BL.fromChunks . (:[])) `fmap` BS.readFile pdfFile
+                   then (Just . BL.fromChunks . (:[])) `fmap`
+                        liftIO (BS.readFile pdfFile)
                    else return Nothing
          -- Note that some things like Missing character warnings
          -- appear in the log but not on stderr, so we prefer the log:
          let logFile = replaceExtension file ".log"
-         logExists <- doesFileExist logFile
+         logExists <- liftIO $ doesFileExist logFile
          log' <- if logExists
-                    then BL.readFile logFile
+                    then liftIO $ BL.readFile logFile
                     else return out
          return (exit, log', pdf)
 
-ms2pdf :: Verbosity
-       -> String
-       -> [String]
-       -> Text
-       -> IO (Either ByteString ByteString)
-ms2pdf verbosity program args source = do
+generic2pdf :: Verbosity
+            -> String
+            -> [String]
+            -> Text
+            -> IO (Either ByteString ByteString)
+generic2pdf verbosity program args source = do
   env' <- getEnvironment
-  when (verbosity >= INFO) $ do
-    putStrLn "[makePDF] Command line:"
-    putStrLn $ program ++ " " ++ unwords (map show args)
-    putStr "\n"
-    putStrLn "[makePDF] Environment:"
-    mapM_ print env'
-    putStr "\n"
-    putStrLn "[makePDF] Contents:\n"
-    putStr $ T.unpack source
-    putStr "\n"
+  when (verbosity >= INFO) $
+    showVerboseInfo Nothing program args env' (T.unpack source)
   (exit, out) <- E.catch
     (pipeProcess (Just env') program args
                      (BL.fromStrict $ UTF8.fromText source))
@@ -353,13 +340,11 @@
                            then E.throwIO $
                                   PandocPDFProgramNotFoundError program
                            else E.throwIO e)
-  when (verbosity >= INFO) $ do
-    BL.hPutStr stdout out
-    putStr "\n"
   return $ case exit of
              ExitFailure _ -> Left out
              ExitSuccess   -> Right out
 
+
 html2pdf  :: Verbosity    -- ^ Verbosity level
           -> String       -- ^ Program (wkhtmltopdf, weasyprint, prince, or path)
           -> [String]     -- ^ Args to program
@@ -375,16 +360,9 @@
   let pdfFileArgName = ["-o" | takeBaseName program == "prince"]
   let programArgs = args ++ [file] ++ 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 " ++ file ++ ":"
-    BL.readFile file >>= BL.putStr
-    putStr "\n"
+  when (verbosity >= INFO) $
+    UTF8.readFile file >>=
+      showVerboseInfo Nothing program programArgs env'
   (exit, out) <- E.catch
     (pipeProcess (Just env') program programArgs BL.empty)
     (\(e :: IOError) -> if isDoesNotExistError e
@@ -412,52 +390,61 @@
 
 context2pdf :: Verbosity    -- ^ Verbosity level
             -> String       -- ^ "context" or path to it
+            -> [String]     -- ^ extra arguments
             -> FilePath     -- ^ temp directory for output
             -> Text         -- ^ ConTeXt source
-            -> IO (Either ByteString ByteString)
-context2pdf verbosity program tmpDir source = inDirectory tmpDir $ do
-  let file = "input.tex"
-  BS.writeFile file $ UTF8.fromText source
-#ifdef _WINDOWS
-  -- note:  we want / even on Windows, for TexLive
-  let tmpDir' = changePathSeparators tmpDir
-#else
-  let tmpDir' = tmpDir
-#endif
-  let programArgs = "--batchmode" : [file]
-  env' <- getEnvironment
-  when (verbosity >= INFO) $ do
-    putStrLn "[makePDF] temp dir:"
-    putStrLn tmpDir'
-    putStrLn "[makePDF] Command line:"
-    putStrLn $ program ++ " " ++ unwords (map show programArgs)
-    putStr "\n"
-    putStrLn "[makePDF] Environment:"
-    mapM_ print env'
-    putStr "\n"
-    putStrLn $ "[makePDF] Contents of " ++ file ++ ":"
-    BL.readFile file >>= BL.putStr
-    putStr "\n"
-  (exit, out) <- E.catch
-    (pipeProcess (Just env') program programArgs BL.empty)
-    (\(e :: IOError) -> if isDoesNotExistError e
-                           then E.throwIO $
-                                  PandocPDFProgramNotFoundError "context"
-                           else E.throwIO e)
-  when (verbosity >= INFO) $ do
-    BL.hPutStr stdout out
-    putStr "\n"
-  let pdfFile = replaceExtension file ".pdf"
-  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 (Just . BL.fromChunks . (:[])) `fmap` BS.readFile pdfFile
-            else return Nothing
-  case (exit, mbPdf) of
-       (ExitFailure _, _)      -> do
-          let logmsg = extractConTeXtMsg out
-          return $ Left logmsg
-       (ExitSuccess, Nothing)  -> return $ Left ""
-       (ExitSuccess, Just pdf) -> return $ Right pdf
+            -> PandocIO (Either ByteString ByteString)
+context2pdf verbosity program pdfargs tmpDir source =
+  liftIO $ inDirectory tmpDir $ do
+    let file = "input.tex"
+    BS.writeFile file $ UTF8.fromText source
+    let programArgs = "--batchmode" : pdfargs ++ [file]
+    env' <- getEnvironment
+    when (verbosity >= INFO) $
+      UTF8.readFile file >>=
+        showVerboseInfo (Just tmpDir) program programArgs env'
+    (exit, out) <- E.catch
+      (pipeProcess (Just env') program programArgs BL.empty)
+      (\(e :: IOError) -> if isDoesNotExistError e
+                             then E.throwIO $
+                                    PandocPDFProgramNotFoundError "context"
+                             else E.throwIO e)
+    when (verbosity >= INFO) $ do
+      BL.hPutStr stdout out
+      putStr "\n"
+    let pdfFile = replaceExtension file ".pdf"
+    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 (Just . BL.fromChunks . (:[])) `fmap` BS.readFile pdfFile
+              else return Nothing
+    case (exit, mbPdf) of
+         (ExitFailure _, _)      -> do
+            let logmsg = extractConTeXtMsg out
+            return $ Left logmsg
+         (ExitSuccess, Nothing)  -> return $ Left ""
+         (ExitSuccess, Just pdf) -> return $ Right pdf
+
+
+showVerboseInfo :: Maybe FilePath
+                -> String
+                -> [String]
+                -> [(String, String)]
+                -> String
+                -> IO ()
+showVerboseInfo mbTmpDir program programArgs env source = do
+  case mbTmpDir of
+    Just tmpDir -> do
+      putStrLn "[makePDF] temp dir:"
+      putStrLn tmpDir
+    Nothing -> return ()
+  putStrLn "[makePDF] Command line:"
+  putStrLn $ program ++ " " ++ unwords (map show programArgs)
+  putStr "\n"
+  putStrLn "[makePDF] Environment:"
+  mapM_ print env
+  putStr "\n"
+  putStrLn $ "[makePDF] Source:"
+  putStrLn source
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
@@ -7,27 +7,9 @@
 {-# LANGUAGE IncoherentInstances        #-}
 {-# LANGUAGE MultiParamTypeClasses      #-}
 {-# LANGUAGE TypeSynonymInstances       #-}
-{-
-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.Parsing
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Pretty.hs b/src/Text/Pandoc/Pretty.hs
--- a/src/Text/Pandoc/Pretty.hs
+++ b/src/Text/Pandoc/Pretty.hs
@@ -1,27 +1,9 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE CPP                        #-}
 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
-{-
-Copyright (C) 2010-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(-1)307  USA
--}
-
 {- |
    Module      : Text.Pandoc.Pretty
-   Copyright   : Copyright (C) 2010-2018 John MacFarlane
+   Copyright   : Copyright (C) 2010-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Process.hs b/src/Text/Pandoc/Process.hs
--- a/src/Text/Pandoc/Process.hs
+++ b/src/Text/Pandoc/Process.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-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.Process
-   Copyright   : Copyright (C) 2013-2018 John MacFarlane
+   Copyright   : Copyright (C) 2013-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
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,28 +1,9 @@
 {-# LANGUAGE MonoLocalBinds      #-}
 {-# LANGUAGE NoImplicitPrelude   #-}
 {-# LANGUAGE ScopedTypeVariables #-}
-
-{-
-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
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Readers/CommonMark.hs b/src/Text/Pandoc/Readers/CommonMark.hs
--- a/src/Text/Pandoc/Readers/CommonMark.hs
+++ b/src/Text/Pandoc/Readers/CommonMark.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2015-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.CommonMark
-   Copyright   : Copyright (C) 2015-2018 John MacFarlane
+   Copyright   : Copyright (C) 2015-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Readers/Creole.hs b/src/Text/Pandoc/Readers/Creole.hs
--- a/src/Text/Pandoc/Readers/Creole.hs
+++ b/src/Text/Pandoc/Readers/Creole.hs
@@ -1,28 +1,5 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
-{-
-  Copyright (C) 2017 Sascha Wilde <wilde@sha-bang.de>
-
-  partly based on all the other readers, especially the work by
-  John MacFarlane <jgm@berkeley.edu> and
-  Alexander Sulfrian <alexander.sulfrian@fu-berlin.de>
-  all bugs are solely created by me.
-
-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.Creole
    Copyright   : Copyright (C) 2017 Sascha Wilde
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,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-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
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
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
@@ -2,27 +2,9 @@
 {-# LANGUAGE CPP               #-}
 {-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE PatternGuards     #-}
-{-
-Copyright (C) 2014-2018 Jesse Rosenthal <jrosenthal@jhu.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.Docx
-   Copyright   : Copyright (C) 2014-2018 Jesse Rosenthal
+   Copyright   : Copyright (C) 2014-2019 Jesse Rosenthal
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
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
@@ -2,7 +2,58 @@
 {-# LANGUAGE FlexibleInstances    #-}
 {-# LANGUAGE PatternGuards        #-}
 {-# LANGUAGE TypeSynonymInstances #-}
+{- |
+   Module      : Text.Pandoc.Readers.Docx.Combine
+   Copyright   : © 2014-2019 Jesse Rosenthal <jrosenthal@jhu.edu>,
+                   2014-2019 John MacFarlane <jgm@berkeley.edu>
+   License     : GNU GPL, version 2 or above
 
+   Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
+   Stability   : alpha
+   Portability : portable
+
+Flatten sequences of elements.
+-}
+
+{-
+The purpose of this module is to combine the formatting of separate
+runs, which have *non-nesting* formatting. Because the formatting
+doesn't nest, you can't actually tell the nesting order until you
+combine with the runs that follow.
+
+For example, say you have a something like `<em><strong>foo</strong>
+bar</em>`. Then in ooxml, you'll get these two runs:
+
+~~~
+<w:r>
+ <w:rPr>
+  <w:b />
+  <w:i />
+ </w:rPr>
+ <w:t>Foo</w:t>
+</w:r>
+<w:r>
+ <w:rPr>
+  <w:i />
+ </w:rPr>
+ <w:t> Bar</w:t>
+</w:r>
+~~~
+
+Note that this is an ideal situation. In practice, it will probably be
+more---if, for example, the user turned italics
+off and then on.
+
+So, when you get the first run, which is marked as both bold and italic,
+you have no idea whether it's `Strong [Emph [Str "Foo"]]` or `Emph
+[Strong [Str "Foo"]]`.
+
+We combine two runs, then, by taking off the formatting that modifies an
+inline, seeing what is shared between them, and rebuilding an inline. We
+fold this to combine the inlines.
+
+-}
+
 module Text.Pandoc.Readers.Docx.Combine ( smushInlines
                                         , smushBlocks
                                         )
@@ -155,7 +206,8 @@
 isAttrModifier _                  = False
 
 smushInlines :: [Inlines] -> Inlines
-smushInlines xs = foldl combineInlines mempty xs
+smushInlines xs = combineInlines xs' mempty
+  where xs' = foldl combineInlines mempty xs
 
 smushBlocks :: [Blocks] -> Blocks
 smushBlocks xs = foldl combineBlocks mempty xs
diff --git a/src/Text/Pandoc/Readers/Docx/Fields.hs b/src/Text/Pandoc/Readers/Docx/Fields.hs
--- a/src/Text/Pandoc/Readers/Docx/Fields.hs
+++ b/src/Text/Pandoc/Readers/Docx/Fields.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2014-2018 Jesse Rosenthal <jrosenthal@jhu.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.Docx.Fields
-   Copyright   : Copyright (C) 2014-2018 Jesse Rosenthal
+   Copyright   : Copyright (C) 2014-2019 Jesse Rosenthal
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
diff --git a/src/Text/Pandoc/Readers/Docx/Lists.hs b/src/Text/Pandoc/Readers/Docx/Lists.hs
--- a/src/Text/Pandoc/Readers/Docx/Lists.hs
+++ b/src/Text/Pandoc/Readers/Docx/Lists.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2014-2018 Jesse Rosenthal <jrosenthal@jhu.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.Docx.Lists
-   Copyright   : Copyright (C) 2014-2018 Jesse Rosenthal
+   Copyright   : Copyright (C) 2014-2019 Jesse Rosenthal
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
diff --git a/src/Text/Pandoc/Readers/Docx/Parse.hs b/src/Text/Pandoc/Readers/Docx/Parse.hs
--- a/src/Text/Pandoc/Readers/Docx/Parse.hs
+++ b/src/Text/Pandoc/Readers/Docx/Parse.hs
@@ -2,28 +2,9 @@
 {-# LANGUAGE FlexibleInstances #-}
 {-# LANGUAGE PatternGuards     #-}
 {-# LANGUAGE ViewPatterns      #-}
-
-{-
-Copyright (C) 2014-2018 Jesse Rosenthal <jrosenthal@jhu.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.Docx.Parse
- Copyright : Copyright (C) 2014-2018 Jesse Rosenthal
+ Copyright : Copyright (C) 2014-2019 Jesse Rosenthal
  License : GNU GPL, version 2 or above
 
  Maintainer : Jesse Rosenthal <jrosenthal@jhu.edu>
@@ -92,6 +73,7 @@
                            , envCharStyles    :: CharStyleMap
                            , envParStyles     :: ParStyleMap
                            , envLocation      :: DocumentLocation
+                           , envDocXmlPath    :: FilePath
                            }
                deriving Show
 
@@ -343,14 +325,26 @@
 
 archiveToDocxWithWarnings :: Archive -> Either DocxError (Docx, [String])
 archiveToDocxWithWarnings archive = do
+  docXmlPath <- case getDocumentXmlPath archive of
+    Just fp -> Right fp
+    Nothing -> Left DocxError
   let notes     = archiveToNotes archive
       comments  = archiveToComments archive
       numbering = archiveToNumbering archive
-      rels      = archiveToRelationships archive
+      rels      = archiveToRelationships archive docXmlPath
       media     = filteredFilesFromArchive archive filePathIsMedia
       (styles, parstyles) = archiveToStyles archive
-      rEnv =
-        ReaderEnv notes comments numbering rels media Nothing styles parstyles InDocument
+      rEnv = ReaderEnv { envNotes = notes
+                       , envComments = comments
+                       , envNumbering = numbering
+                       , envRelationships = rels
+                       , envMedia = media
+                       , envFont = Nothing
+                       , envCharStyles = styles
+                       , envParStyles = parstyles
+                       , envLocation = InDocument
+                       , envDocXmlPath = docXmlPath
+                       }
       rState = ReaderState { stateWarnings = []
                            , stateFldCharState = FldCharClosed
                            }
@@ -359,11 +353,26 @@
     Right doc -> Right (Docx doc, stateWarnings st)
     Left e    -> Left e
 
-
+getDocumentXmlPath :: Archive -> Maybe String
+getDocumentXmlPath zf = do
+  entry <- findEntryByPath "_rels/.rels" zf
+  relsElem <- (parseXMLDoc . UTF8.toStringLazy . fromEntry) entry
+  let rels = filterChildrenName (\n -> qName n == "Relationship") relsElem
+  rel <- listToMaybe $
+         filter (\e -> findAttr (QName "Type" Nothing Nothing) e ==
+                       Just "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument")
+         rels
+  fp <- findAttr (QName "Target" Nothing Nothing) rel
+  -- sometimes there will be a leading slash, which windows seems to
+  -- have trouble with.
+  return $ case fp of
+    '/' : fp' -> fp'
+    _         -> fp
 
 archiveToDocument :: Archive -> D Document
 archiveToDocument zf = do
-  entry <- maybeToD $ findEntryByPath "word/document.xml" zf
+  docPath <- asks envDocXmlPath
+  entry <- maybeToD $ findEntryByPath docPath zf
   docElem <- maybeToD $ (parseXMLDoc . UTF8.toStringLazy . fromEntry) entry
   let namespaces = elemToNameSpaces docElem
   bodyElem <- maybeToD $ findChildByName namespaces "w" "body" docElem
@@ -458,8 +467,8 @@
         Just e  -> elemToNameSpaces e
         Nothing -> []
       ns = unionBy (\x y -> fst x == fst y) fn_namespaces en_namespaces
-      fn = fnElem >>= elemToNotes ns "footnote"
-      en = enElem >>= elemToNotes ns "endnote"
+      fn = fnElem >>= walkDocument ns >>= elemToNotes ns "footnote"
+      en = enElem >>= walkDocument ns >>= elemToNotes ns "endnote"
   in
    Notes ns fn en
 
@@ -470,17 +479,21 @@
       cmts_namespaces = case cmtsElem of
         Just e  -> elemToNameSpaces e
         Nothing -> []
-      cmts = elemToComments cmts_namespaces <$> cmtsElem
+      cmts = elemToComments cmts_namespaces <$> (cmtsElem >>= walkDocument cmts_namespaces)
   in
     case cmts of
       Just c  -> Comments cmts_namespaces c
       Nothing -> Comments cmts_namespaces M.empty
 
-filePathToRelType :: FilePath -> Maybe DocumentLocation
-filePathToRelType "word/_rels/document.xml.rels"  = Just InDocument
-filePathToRelType "word/_rels/footnotes.xml.rels" = Just InFootnote
-filePathToRelType "word/_rels/endnotes.xml.rels"  = Just InEndnote
-filePathToRelType _                               = Nothing
+filePathToRelType :: FilePath -> FilePath -> Maybe DocumentLocation
+filePathToRelType "word/_rels/footnotes.xml.rels" _ = Just InFootnote
+filePathToRelType "word/_rels/endnotes.xml.rels" _ = Just InEndnote
+-- -- to see if it's a documentPath, we have to check against the dynamic
+-- -- docPath specified in "_rels/.rels"
+filePathToRelType path docXmlPath =
+  if path == "word/_rels/" ++ (takeFileName docXmlPath) ++ ".rels"
+  then Just InDocument
+  else Nothing
 
 relElemToRelationship :: DocumentLocation -> Element -> Maybe Relationship
 relElemToRelationship relType element | qName (elName element) == "Relationship" =
@@ -490,16 +503,17 @@
     return $ Relationship relType relId target
 relElemToRelationship _ _ = Nothing
 
-filePathToRelationships :: Archive -> FilePath -> [Relationship]
-filePathToRelationships ar fp | Just relType <- filePathToRelType fp
-                              , Just entry <- findEntryByPath fp ar
-                              , Just relElems <- (parseXMLDoc . UTF8.toStringLazy . fromEntry) entry =
+filePathToRelationships :: Archive -> FilePath -> FilePath ->  [Relationship]
+filePathToRelationships ar docXmlPath fp
+  | Just relType <- filePathToRelType fp docXmlPath
+  , Just entry <- findEntryByPath fp ar
+  , Just relElems <- (parseXMLDoc . UTF8.toStringLazy . fromEntry) entry =
   mapMaybe (relElemToRelationship relType) $ elChildren relElems
-filePathToRelationships _ _ = []
+filePathToRelationships _ _ _ = []
 
-archiveToRelationships :: Archive -> [Relationship]
-archiveToRelationships archive =
-  concatMap (filePathToRelationships archive) $ filesInArchive archive
+archiveToRelationships :: Archive -> FilePath -> [Relationship]
+archiveToRelationships archive docXmlPath =
+  concatMap (filePathToRelationships archive docXmlPath) $ filesInArchive archive
 
 filePathIsMedia :: FilePath -> Bool
 filePathIsMedia fp =
diff --git a/src/Text/Pandoc/Readers/Docx/StyleMap.hs b/src/Text/Pandoc/Readers/Docx/StyleMap.hs
--- a/src/Text/Pandoc/Readers/Docx/StyleMap.hs
+++ b/src/Text/Pandoc/Readers/Docx/StyleMap.hs
@@ -1,4 +1,17 @@
 {-# LANGUAGE NoImplicitPrelude #-}
+{- |
+   Module      : Text.Pandoc.Readers.Docx.StyleMaps
+   Copyright   : © 2014-2019 Jesse Rosenthal <jrosenthal@jhu.edu>,
+                   2014-2019 John MacFarlane <jgm@berkeley.edu>,
+                   2015 Nikolay Yakimov <root@livid.pp.ru>
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
+   Stability   : alpha
+   Portability : portable
+
+Mappings of element styles (word to pandoc-internal).
+-}
 module Text.Pandoc.Readers.Docx.StyleMap (  StyleMaps(..)
                                           , alterMap
                                           , getMap
diff --git a/src/Text/Pandoc/Readers/Docx/Util.hs b/src/Text/Pandoc/Readers/Docx/Util.hs
--- a/src/Text/Pandoc/Readers/Docx/Util.hs
+++ b/src/Text/Pandoc/Readers/Docx/Util.hs
@@ -1,4 +1,17 @@
 {-# LANGUAGE NoImplicitPrelude #-}
+{- |
+   Module      : Text.Pandoc.Readers.Docx.StyleMaps
+   Copyright   : © 2014-2019 Jesse Rosenthal <jrosenthal@jhu.edu>,
+                   2014-2019 John MacFarlane <jgm@berkeley.edu>,
+                   2015 Nikolay Yakimov <root@livid.pp.ru>
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
+   Stability   : alpha
+   Portability : portable
+
+Docx reader utility functions.
+-}
 module Text.Pandoc.Readers.Docx.Util (
                                         NameSpaces
                                       , elemName
diff --git a/src/Text/Pandoc/Readers/DokuWiki.hs b/src/Text/Pandoc/Readers/DokuWiki.hs
--- a/src/Text/Pandoc/Readers/DokuWiki.hs
+++ b/src/Text/Pandoc/Readers/DokuWiki.hs
@@ -2,28 +2,9 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE TupleSections     #-}
-
-{-
-  Copyright (C) 2018-2019 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.DokuWiki
-   Copyright   : Copyright (C) 2018 Alexander Krotov
+   Copyright   : Copyright (C) 2018-2019 Alexander Krotov
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Alexander Krotov <ilabdsf@gmail.com>
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,27 +1,9 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE TupleSections     #-}
 {-# LANGUAGE ViewPatterns      #-}
-{-
-Copyright (C) 2014-2018 Matthew Pickering
-
-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
+   Copyright   : Copyright (C) 2014-2019 Matthew Pickering
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Readers/FB2.hs b/src/Text/Pandoc/Readers/FB2.hs
--- a/src/Text/Pandoc/Readers/FB2.hs
+++ b/src/Text/Pandoc/Readers/FB2.hs
@@ -1,26 +1,8 @@
 {-# 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
+   Copyright   : Copyright (C) 2018-2019 Alexander Krotov
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Alexander Krotov <ilabdsf@gmail.com>
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
@@ -4,27 +4,9 @@
 {-# LANGUAGE MultiParamTypeClasses #-}
 {-# LANGUAGE OverloadedStrings     #-}
 {-# LANGUAGE ViewPatterns          #-}
-{-
-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.HTML
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Readers/Ipynb.hs b/src/Text/Pandoc/Readers/Ipynb.hs
--- a/src/Text/Pandoc/Readers/Ipynb.hs
+++ b/src/Text/Pandoc/Readers/Ipynb.hs
@@ -4,24 +4,6 @@
 {-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE FlexibleContexts  #-}
 {-# LANGUAGE ScopedTypeVariables #-}
-{-
-Copyright (C) 2019 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.Ipynb
    Copyright   : Copyright (C) 2019 John MacFarlane
@@ -36,6 +18,7 @@
 module Text.Pandoc.Readers.Ipynb ( readIpynb )
 where
 import Prelude
+import Data.List (isPrefixOf)
 import Data.Maybe (fromMaybe)
 import Data.Digest.Pure.SHA (sha1, showDigest)
 import Text.Pandoc.Options
@@ -46,6 +29,7 @@
 import Text.Pandoc.Class
 import Text.Pandoc.MIME (extensionFromMimeType)
 import Text.Pandoc.UTF8
+import Text.Pandoc.Walk (walk)
 import Text.Pandoc.Error
 import Data.Text (Text)
 import qualified Data.Map as M
@@ -55,7 +39,6 @@
 import Data.Aeson as Aeson
 import Control.Monad.Except (throwError)
 import Text.Pandoc.Readers.Markdown (readMarkdown)
-import Text.Pandoc.Readers.HTML (readHtml)
 
 readIpynb :: PandocMonad m => ReaderOptions -> Text -> m Pandoc
 readIpynb opts t = do
@@ -95,7 +78,7 @@
   mapM_ addAttachment attachments
   case cellType c of
     Ipynb.Markdown -> do
-      Pandoc _ bs <- readMarkdown opts source
+      Pandoc _ bs <- walk fixImage <$> readMarkdown opts source
       return $ B.divWith ("",["cell","markdown"],kvs)
              $ B.fromList bs
     Ipynb.Heading lev -> do
@@ -122,6 +105,12 @@
         B.codeBlockWith ("",[lang],[]) (T.unpack source)
         <> outputBlocks
 
+-- Remove attachment: prefix from images...
+fixImage :: Inline -> Inline
+fixImage (Image attr lab (src,tit))
+  | "attachment:" `isPrefixOf` src = Image attr lab (drop 11 src, tit)
+fixImage x = x
+
 addAttachment :: PandocMonad m => (Text, MimeBundle) -> m ()
 addAttachment (fname, mimeBundle) = do
   let fp = T.unpack fname
@@ -161,23 +150,14 @@
 -- the output format.
 handleData :: PandocMonad m
            => ReaderOptions -> JSONMeta -> MimeBundle -> m B.Blocks
-handleData opts metadata (MimeBundle mb) = do
-  let mimePairs = M.toList mb
-
-  results <- mapM dataBlock mimePairs
-
-  -- return the result with highest priority:
-
-  let highest = maximum (0 : map fst results)
-  return $ case [r | (pr, r) <- results, pr == highest] of
-             x:_  -> x
-             []   -> mempty
+handleData opts metadata (MimeBundle mb) =
+  mconcat <$> mapM dataBlock (M.toList mb)
 
   where
 
     exts = readerExtensions opts
 
-    dataBlock :: PandocMonad m => (MimeType, MimeData) -> m (Int, B.Blocks)
+    dataBlock :: PandocMonad m => (MimeType, MimeData) -> m B.Blocks
     dataBlock (mt, BinaryData bs)
      | "image/" `T.isPrefixOf` mt
       = do
@@ -198,29 +178,26 @@
               Nothing  -> ""
               Just ext -> '.':ext
       insertMedia fname (Just mt') bl
-      return (3, B.para $ B.imageWith ("",[],metaPairs) fname "" mempty)
-
-    dataBlock (_, BinaryData _) = return (0, mempty)
+      return $ B.para $ B.imageWith ("",[],metaPairs) fname "" mempty
+     | otherwise = return mempty
 
     dataBlock ("text/html", TextualData t)
       | extensionEnabled Ext_raw_html exts
-        = return (2, B.rawBlock "html" $ T.unpack t)
-      | otherwise = do -- try parsing the HTML
-          Pandoc _ bls <- readHtml opts t
-          return (1, B.fromList bls)
+        = return $ B.rawBlock "html" $ T.unpack t
+      | otherwise = return mempty
 
-    dataBlock ("text/latex", TextualData t) =
-      return $ if extensionEnabled Ext_raw_tex exts
-                  then (2, B.rawBlock "latex" $ T.unpack t)
-                  else (0, mempty)
+    dataBlock ("text/latex", TextualData t)
+      | extensionEnabled Ext_raw_tex exts
+        = return $ B.rawBlock "latex" $ T.unpack t
+      | otherwise = return mempty
 
     dataBlock ("text/plain", TextualData t) =
-      return (0, B.codeBlock $ T.unpack t)
+      return $ B.codeBlock $ T.unpack t
 
     dataBlock (_, JsonData v) =
-      return (2, B.codeBlockWith ("",["json"],[]) $ toStringLazy $ encode v)
+      return $ B.codeBlockWith ("",["json"],[]) $ toStringLazy $ encode v
 
-    dataBlock _ = return (0, mempty)
+    dataBlock _ = return mempty
 
 jsonMetaToMeta :: JSONMeta -> M.Map String MetaValue
 jsonMetaToMeta = M.mapKeys T.unpack . M.map valueToMetaValue
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,26 +1,8 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# 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
+   Copyright   : Copyright (C) 2017-2019 Hamish Mackenzie
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -57,7 +39,6 @@
                           , jatsQuoteType    :: QuoteType
                           , jatsMeta         :: Meta
                           , jatsBook         :: Bool
-                          , jatsFigureTitle  :: Inlines
                           , jatsContent      :: [Content]
                           } deriving Show
 
@@ -66,7 +47,6 @@
                  , jatsQuoteType = DoubleQuote
                  , jatsMeta = mempty
                  , jatsBook = False
-                 , jatsFigureTitle = mempty
                  , jatsContent = [] }
 
 
@@ -153,21 +133,18 @@
 
 -- function that is used by both graphic (in parseBlock)
 -- and inline-graphic (in parseInline)
-getGraphic :: PandocMonad m => Element -> JATS m Inlines
-getGraphic e = do
+getGraphic :: PandocMonad m
+           => Maybe (Inlines, String) -> Element -> JATS m Inlines
+getGraphic mbfigdata e = do
   let atVal a = attrValue a e
-      attr = (atVal "id", words $ atVal "role", [])
+      (ident, title, caption) =
+         case mbfigdata of
+           Just (capt, i) -> (i, "fig:" <> atVal "title", capt)
+           Nothing        -> (atVal "id", atVal "title",
+                              text (atVal "alt-text"))
+      attr = (ident, words $ atVal "role", [])
       imageUrl = atVal "href"
-      captionOrLabel = case filterChild (\x -> named "caption" x
-                                            || named "label" x) e of
-                        Nothing -> return mempty
-                        Just z  -> mconcat <$>
-                                         mapM parseInline (elContent z)
-  figTitle <- gets jatsFigureTitle
-  let (caption, title) = if isNull figTitle
-                            then (captionOrLabel, atVal "title")
-                            else (return figTitle, "fig:")
-  fmap (imageWith attr imageUrl title) caption
+  return $ imageWith attr imageUrl title caption
 
 getBlocks :: PandocMonad m => Element -> JATS m Blocks
 getBlocks e =  mconcat <$>
@@ -197,14 +174,17 @@
                         <$> listitems
         "def-list" -> definitionList <$> deflistitems
         "sec" -> gets jatsSectionLevel >>= sect . (+1)
-        "graphic" -> para <$> getGraphic e
+        "graphic" -> para <$> getGraphic Nothing e
         "journal-meta" -> parseMetadata e
         "article-meta" -> parseMetadata e
         "custom-meta" -> parseMetadata e
         "title" -> return mempty -- processed by header
         "table" -> parseTable
-        "fig" -> divWith (attrValue "id" e, ["fig"], []) <$> getBlocks e
-        "table-wrap" -> divWith (attrValue "id" e, ["table-wrap"], []) <$> getBlocks e
+        "fig" -> parseFigure
+        "fig-group" -> divWith (attrValue "id" e, ["fig-group"], [])
+                          <$> getBlocks e
+        "table-wrap" -> divWith (attrValue "id" e, ["table-wrap"], [])
+                          <$> getBlocks e
         "caption" -> divWith (attrValue "id" e, ["caption"], []) <$> sect 6
         "ref-list" -> parseRefList e
         "?xml"  -> return mempty
@@ -247,6 +227,20 @@
                      terms' <- mapM getInlines terms
                      items' <- mapM getBlocks items
                      return (mconcat $ intersperse (str "; ") terms', items')
+         parseFigure = do
+           -- if a simple caption and single graphic, we emit a standard
+           -- implicit figure.  otherwise, we emit a div with the contents
+           case filterChildren (named "graphic") e of
+                  [g] -> do
+                         caption <- case filterChild (named "caption") e of
+                                           Just t  -> mconcat .
+                                             intersperse linebreak <$>
+                                             mapM getInlines
+                                             (filterChildren (const True) t)
+                                           Nothing -> return mempty
+                         img <- getGraphic (Just (caption, attrValue "id" e)) g
+                         return $ para $ img
+                  _   -> divWith (attrValue "id" e, ["fig"], []) <$> getBlocks e
          parseTable = do
                       let isCaption x = named "title" x || named "caption" x
                       caption <- case filterChild isCaption e of
@@ -456,7 +450,7 @@
         "code" -> codeWithLang
         "monospace" -> codeWithLang
 
-        "inline-graphic" -> getGraphic e
+        "inline-graphic" -> getGraphic Nothing e
         "disp-quote" -> do
             qt <- gets jatsQuoteType
             let qt' = if qt == SingleQuote then DoubleQuote else SingleQuote
@@ -470,16 +464,19 @@
         "xref" -> do
             ils <- innerInlines
             let rid = attrValue "rid" e
+            let rids = words rid
             let refType = ("ref-type",) <$> maybeAttrValue "ref-type" e
             let attr = (attrValue "id" e, [], maybeToList refType)
             return $ if refType == Just ("ref-type","bibr")
-                        then cite [Citation{
-                                         citationId = rid
-                                       , citationPrefix = []
-                                       , citationSuffix = []
-                                       , citationMode = NormalCitation
-                                       , citationNoteNum = 0
-                                       , citationHash = 0}] ils
+                        then cite
+                             (map (\id' ->
+                                     Citation{ citationId = id'
+                                             , citationPrefix = []
+                                             , citationSuffix = []
+                                             , citationMode = NormalCitation
+                                             , citationNoteNum = 0
+                                             , citationHash = 0}) rids)
+                             ils
                         else linkWith attr ('#' : rid) "" ils
         "ext-link" -> do
              ils <- innerInlines
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
@@ -4,27 +4,9 @@
 {-# LANGUAGE OverloadedStrings     #-}
 {-# LANGUAGE PatternGuards         #-}
 {-# LANGUAGE ScopedTypeVariables   #-}
-{-
-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.LaTeX
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Readers/LaTeX/Lang.hs b/src/Text/Pandoc/Readers/LaTeX/Lang.hs
--- a/src/Text/Pandoc/Readers/LaTeX/Lang.hs
+++ b/src/Text/Pandoc/Readers/LaTeX/Lang.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 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.LaTeX.Lang
-   Copyright   : Copyright (C) 2018 John MacFarlane
+   Copyright   : Copyright (C) 2018-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Readers/LaTeX/Parsing.hs b/src/Text/Pandoc/Readers/LaTeX/Parsing.hs
--- a/src/Text/Pandoc/Readers/LaTeX/Parsing.hs
+++ b/src/Text/Pandoc/Readers/LaTeX/Parsing.hs
@@ -3,27 +3,9 @@
 {-# LANGUAGE MultiParamTypeClasses #-}
 {-# LANGUAGE OverloadedStrings     #-}
 {-# LANGUAGE ScopedTypeVariables   #-}
-{-
-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.LaTeX.Parsing
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -612,19 +594,19 @@
 braced' getTok n =
   handleEgroup <|> handleBgroup <|> handleOther
   where handleEgroup = do
-          t <- egroup
+          t <- symbol '}'
           if n == 1
              then return []
              else (t:) <$> braced' getTok (n - 1)
         handleBgroup = do
-          t <- bgroup
+          t <- symbol '{'
           (t:) <$> braced' getTok (n + 1)
         handleOther = do
           t <- getTok
           (t:) <$> braced' getTok n
 
 braced :: PandocMonad m => LP m [Tok]
-braced = bgroup *> braced' anyTok 1
+braced = symbol '{' *> braced' anyTok 1
 
 -- URLs require special handling, because they can contain %
 -- characters.  So we retonenize comments as we go...
diff --git a/src/Text/Pandoc/Readers/LaTeX/Types.hs b/src/Text/Pandoc/Readers/LaTeX/Types.hs
--- a/src/Text/Pandoc/Readers/LaTeX/Types.hs
+++ b/src/Text/Pandoc/Readers/LaTeX/Types.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2017-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.LaTeX.Types
-   Copyright   : Copyright (C) 2017-2018 John MacFarlane
+   Copyright   : Copyright (C) 2017-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Readers/Man.hs b/src/Text/Pandoc/Readers/Man.hs
--- a/src/Text/Pandoc/Readers/Man.hs
+++ b/src/Text/Pandoc/Readers/Man.hs
@@ -1,28 +1,7 @@
 {-# LANGUAGE FlexibleContexts #-}
-
-{-
-  Copyright (C) 2018 Yan Pashkovsky <yanp.bugz@gmail.com>
-                     and John MacFarlane
-
-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.Man
-   Copyright   : Copyright (C) 2018 Yan Pashkovsky and John MacFarlane
+   Copyright   : Copyright (C) 2018-2019 Yan Pashkovsky and John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Yan Pashkovsky <yanp.bugz@gmail.com>
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
@@ -2,28 +2,9 @@
 {-# LANGUAGE RelaxedPolyRec      #-}
 {-# LANGUAGE ScopedTypeVariables #-}
 {-# LANGUAGE TupleSections #-}
-
-{-
-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.Markdown
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -249,12 +230,12 @@
 
 -- | Read a YAML string and convert it to pandoc metadata.
 -- String scalars in the YAML are parsed as Markdown.
-yamlToMeta :: PandocMonad m => BS.ByteString -> m Meta
-yamlToMeta bstr = do
+yamlToMeta :: PandocMonad m => ReaderOptions -> BS.ByteString -> m Meta
+yamlToMeta opts bstr = do
   let parser = do
         meta <- yamlBsToMeta bstr
         return $ runF meta defaultParserState
-  parsed <- readWithM parser def ""
+  parsed <- readWithM parser def{ stateOptions = opts } ""
   case parsed of
     Right result -> return result
     Left e       -> throwError e
@@ -284,21 +265,22 @@
 toMetaValue :: PandocMonad m
             => Text -> MarkdownParser m (F MetaValue)
 toMetaValue x =
-  parseFromString' parser' (T.unpack x)
-  where parser' = (asInlines <$> ((trimInlinesF . mconcat)
-                       <$> try (guard (not endsWithNewline)
-                                *> manyTill inline eof)))
-                  <|> (asBlocks <$> parseBlocks)
+   -- Note: a standard quoted or unquoted YAML value will
+   -- not end in a newline, but a "block" set off with
+   -- `|` or `>` will.
+   if (T.pack "\n") `T.isSuffixOf` x
+      then parseFromString' (asBlocks <$> parseBlocks) (xstring <> "\n")
+      else parseFromString'
+             ((asInlines <$> try pInlines) <|> (asBlocks <$> parseBlocks))
+             xstring
+  where pInlines = trimInlinesF . mconcat <$> manyTill inline eof
         asBlocks p = do
           p' <- p
           return $ MetaBlocks (B.toList p')
         asInlines p = do
           p' <- p
           return $ MetaInlines (B.toList p')
-        endsWithNewline = T.pack "\n" `T.isSuffixOf` x
-        -- Note: a standard quoted or unquoted YAML value will
-        -- not end in a newline, but a "block" set off with
-        -- `|` or `>` will.
+        xstring = T.unpack x
 
 checkBoolean :: Text -> Maybe Bool
 checkBoolean t =
@@ -720,8 +702,9 @@
   blankline
   contents <- intercalate "\n" <$>
                  manyTill (gobbleAtMostSpaces indentLevel >> anyLine)
-                          (blockDelimiter (== c) (Just size))
-  blanklines
+                          (try $ do
+                            blockDelimiter (== c) (Just size)
+                            blanklines)
   return $ return $
     case rawattr of
           Left syn   -> B.rawBlock syn contents
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,27 +1,9 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE RelaxedPolyRec #-}
 -- RelaxedPolyRec needed for inlinesBetween on GHC < 7
-{-
-  Copyright (C) 2012-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.MediaWiki
-   Copyright   : Copyright (C) 2012-2018 John MacFarlane
+   Copyright   : Copyright (C) 2012-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
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,27 +1,9 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE FlexibleContexts #-}
 {-# LANGUAGE TupleSections #-}
-{-
-  Copyright (C) 2017-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.Muse
-   Copyright   : Copyright (C) 2017-2018 Alexander Krotov
+   Copyright   : Copyright (C) 2017-2019 Alexander Krotov
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Alexander Krotov <ilabdsf@gmail.com>
@@ -481,12 +463,18 @@
   guard $ not inPara
   first (fmap B.para) <$> paraContentsUntil end
 
-noteMarker :: PandocMonad m => MuseParser m String
-noteMarker = try $ (:)
-  <$  char '['
+noteMarker' :: PandocMonad m
+            => Char
+            -> Char
+            -> MuseParser m String
+noteMarker' l r = try $ (\x y -> l:x:y ++ [r])
+  <$ char l
   <*> oneOf "123456789"
-  <*> manyTill digit (char ']')
+  <*> manyTill digit (char r)
 
+noteMarker :: PandocMonad m => MuseParser m String
+noteMarker = noteMarker' '[' ']' <|> noteMarker' '{' '}'
+
 addNote :: PandocMonad m
         => String
         -> SourcePos
@@ -797,7 +785,7 @@
   return $ do
     notes <- asksF museNotes
     case M.lookup ref notes of
-      Nothing -> return $ B.str $ "[" ++ ref ++ "]"
+      Nothing -> return $ B.str ref
       Just (_pos, contents) -> do
         st <- askF
         let contents' = runF contents st { museNotes = M.delete ref (museNotes st) }
diff --git a/src/Text/Pandoc/Readers/Native.hs b/src/Text/Pandoc/Readers/Native.hs
--- a/src/Text/Pandoc/Readers/Native.hs
+++ b/src/Text/Pandoc/Readers/Native.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2011-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.Native
-   Copyright   : Copyright (C) 2011-2018 John MacFarlane
+   Copyright   : Copyright (C) 2011-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
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,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-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
+   Copyright   : Copyright (C) 2013-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Readers/Odt.hs b/src/Text/Pandoc/Readers/Odt.hs
--- a/src/Text/Pandoc/Readers/Odt.hs
+++ b/src/Text/Pandoc/Readers/Odt.hs
@@ -1,24 +1,5 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE PatternGuards #-}
-
-{-
-Copyright (C) 2015 Martin Linnemann <theCodingMarlin@googlemail.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.Reader.Odt
    Copyright   : Copyright (C) 2015 Martin Linnemann
diff --git a/src/Text/Pandoc/Readers/Odt/Arrows/State.hs b/src/Text/Pandoc/Readers/Odt/Arrows/State.hs
--- a/src/Text/Pandoc/Readers/Odt/Arrows/State.hs
+++ b/src/Text/Pandoc/Readers/Odt/Arrows/State.hs
@@ -1,24 +1,6 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE FlexibleInstances #-}
 {-# LANGUAGE TupleSections     #-}
-{-
-Copyright (C) 2015 Martin Linnemann <theCodingMarlin@googlemail.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.Odt.Arrows.State
    Copyright   : Copyright (C) 2015 Martin Linnemann
diff --git a/src/Text/Pandoc/Readers/Odt/Arrows/Utils.hs b/src/Text/Pandoc/Readers/Odt/Arrows/Utils.hs
--- a/src/Text/Pandoc/Readers/Odt/Arrows/Utils.hs
+++ b/src/Text/Pandoc/Readers/Odt/Arrows/Utils.hs
@@ -1,22 +1,4 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2015 Martin Linnemann <theCodingMarlin@googlemail.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.Odt.Arrows.Utils
    Copyright   : Copyright (C) 2015 Martin Linnemann
diff --git a/src/Text/Pandoc/Readers/Odt/Base.hs b/src/Text/Pandoc/Readers/Odt/Base.hs
--- a/src/Text/Pandoc/Readers/Odt/Base.hs
+++ b/src/Text/Pandoc/Readers/Odt/Base.hs
@@ -1,21 +1,3 @@
-{-
-Copyright (C) 2015 Martin Linnemann <theCodingMarlin@googlemail.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.Odt.Base
    Copyright   : Copyright (C) 2015 Martin Linnemann
diff --git a/src/Text/Pandoc/Readers/Odt/ContentReader.hs b/src/Text/Pandoc/Readers/Odt/ContentReader.hs
--- a/src/Text/Pandoc/Readers/Odt/ContentReader.hs
+++ b/src/Text/Pandoc/Readers/Odt/ContentReader.hs
@@ -4,25 +4,6 @@
 {-# LANGUAGE RecordWildCards #-}
 {-# LANGUAGE TupleSections   #-}
 {-# LANGUAGE ViewPatterns    #-}
-
-{-
-Copyright (C) 2015 Martin Linnemann <theCodingMarlin@googlemail.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.Odt.ContentReader
    Copyright   : Copyright (C) 2015 Martin Linnemann
diff --git a/src/Text/Pandoc/Readers/Odt/Generic/Fallible.hs b/src/Text/Pandoc/Readers/Odt/Generic/Fallible.hs
--- a/src/Text/Pandoc/Readers/Odt/Generic/Fallible.hs
+++ b/src/Text/Pandoc/Readers/Odt/Generic/Fallible.hs
@@ -1,24 +1,4 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-
-
-{-
-Copyright (C) 2015 Martin Linnemann <theCodingMarlin@googlemail.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.Odt.Generic.Fallible
    Copyright   : Copyright (C) 2015 Martin Linnemann
diff --git a/src/Text/Pandoc/Readers/Odt/Generic/Namespaces.hs b/src/Text/Pandoc/Readers/Odt/Generic/Namespaces.hs
--- a/src/Text/Pandoc/Readers/Odt/Generic/Namespaces.hs
+++ b/src/Text/Pandoc/Readers/Odt/Generic/Namespaces.hs
@@ -1,22 +1,4 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2015 Martin Linnemann <theCodingMarlin@googlemail.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.Odt.Generic.Namespaces
    Copyright   : Copyright (C) 2015 Martin Linnemann
diff --git a/src/Text/Pandoc/Readers/Odt/Generic/SetMap.hs b/src/Text/Pandoc/Readers/Odt/Generic/SetMap.hs
--- a/src/Text/Pandoc/Readers/Odt/Generic/SetMap.hs
+++ b/src/Text/Pandoc/Readers/Odt/Generic/SetMap.hs
@@ -1,22 +1,4 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2015 Martin Linnemann <theCodingMarlin@googlemail.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.Odt.Generic.SetMap
    Copyright   : Copyright (C) 2015 Martin Linnemann
diff --git a/src/Text/Pandoc/Readers/Odt/Generic/Utils.hs b/src/Text/Pandoc/Readers/Odt/Generic/Utils.hs
--- a/src/Text/Pandoc/Readers/Odt/Generic/Utils.hs
+++ b/src/Text/Pandoc/Readers/Odt/Generic/Utils.hs
@@ -1,27 +1,6 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-
-
 {-# LANGUAGE TypeOperators #-}
 {-# LANGUAGE ViewPatterns  #-}
-
-{-
-Copyright (C) 2015 Martin Linnemann <theCodingMarlin@googlemail.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.Reader.Odt.Generic.Utils
    Copyright   : Copyright (C) 2015 Martin Linnemann
diff --git a/src/Text/Pandoc/Readers/Odt/Generic/XMLConverter.hs b/src/Text/Pandoc/Readers/Odt/Generic/XMLConverter.hs
--- a/src/Text/Pandoc/Readers/Odt/Generic/XMLConverter.hs
+++ b/src/Text/Pandoc/Readers/Odt/Generic/XMLConverter.hs
@@ -4,25 +4,6 @@
 {-# LANGUAGE GADTs           #-}
 {-# LANGUAGE PatternGuards   #-}
 {-# LANGUAGE RecordWildCards #-}
-
-{-
-Copyright (C) 2015 Martin Linnemann <theCodingMarlin@googlemail.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.Odt.Generic.XMLConverter
    Copyright   : Copyright (C) 2015 Martin Linnemann
diff --git a/src/Text/Pandoc/Readers/Odt/Namespaces.hs b/src/Text/Pandoc/Readers/Odt/Namespaces.hs
--- a/src/Text/Pandoc/Readers/Odt/Namespaces.hs
+++ b/src/Text/Pandoc/Readers/Odt/Namespaces.hs
@@ -1,22 +1,4 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2015 Martin Linnemann <theCodingMarlin@googlemail.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.Reader.Odt.Namespaces
    Copyright   : Copyright (C) 2015 Martin Linnemann
diff --git a/src/Text/Pandoc/Readers/Odt/StyleReader.hs b/src/Text/Pandoc/Readers/Odt/StyleReader.hs
--- a/src/Text/Pandoc/Readers/Odt/StyleReader.hs
+++ b/src/Text/Pandoc/Readers/Odt/StyleReader.hs
@@ -3,25 +3,6 @@
 {-# LANGUAGE Arrows          #-}
 {-# LANGUAGE RecordWildCards #-}
 {-# LANGUAGE TupleSections   #-}
-
-{-
-Copyright (C) 2015 Martin Linnemann <theCodingMarlin@googlemail.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.Odt.StyleReader
    Copyright   : Copyright (C) 2015 Martin Linnemann
diff --git a/src/Text/Pandoc/Readers/Org.hs b/src/Text/Pandoc/Readers/Org.hs
--- a/src/Text/Pandoc/Readers/Org.hs
+++ b/src/Text/Pandoc/Readers/Org.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2014-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-
-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.Org
-   Copyright   : Copyright (C) 2014-2018 Albert Krewinkel
+   Copyright   : Copyright (C) 2014-2019 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
diff --git a/src/Text/Pandoc/Readers/Org/BlockStarts.hs b/src/Text/Pandoc/Readers/Org/BlockStarts.hs
--- a/src/Text/Pandoc/Readers/Org/BlockStarts.hs
+++ b/src/Text/Pandoc/Readers/Org/BlockStarts.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2014-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-
-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.Org.BlockStarts
-   Copyright   : Copyright (C) 2014-2018 Albert Krewinkel
+   Copyright   : Copyright (C) 2014-2019 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
diff --git a/src/Text/Pandoc/Readers/Org/Blocks.hs b/src/Text/Pandoc/Readers/Org/Blocks.hs
--- a/src/Text/Pandoc/Readers/Org/Blocks.hs
+++ b/src/Text/Pandoc/Readers/Org/Blocks.hs
@@ -1,26 +1,9 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2014-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-
-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
--}
 {-# LANGUAGE FlexibleContexts #-}
 {-# LANGUAGE RecordWildCards  #-}
 {- |
    Module      : Text.Pandoc.Readers.Org.Blocks
-   Copyright   : Copyright (C) 2014-2018 Albert Krewinkel
+   Copyright   : Copyright (C) 2014-2019 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
diff --git a/src/Text/Pandoc/Readers/Org/DocumentTree.hs b/src/Text/Pandoc/Readers/Org/DocumentTree.hs
--- a/src/Text/Pandoc/Readers/Org/DocumentTree.hs
+++ b/src/Text/Pandoc/Readers/Org/DocumentTree.hs
@@ -1,25 +1,8 @@
-{-
-Copyright (C) 2014-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-
-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
--}
 {-# LANGUAGE FlexibleContexts #-}
 {-# LANGUAGE NoImplicitPrelude #-}
 {- |
    Module      : Text.Pandoc.Readers.Org.DocumentTree
-   Copyright   : Copyright (C) 2014-2018 Albert Krewinkel
+   Copyright   : Copyright (C) 2014-2019 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
diff --git a/src/Text/Pandoc/Readers/Org/ExportSettings.hs b/src/Text/Pandoc/Readers/Org/ExportSettings.hs
--- a/src/Text/Pandoc/Readers/Org/ExportSettings.hs
+++ b/src/Text/Pandoc/Readers/Org/ExportSettings.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2016-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-
-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.Org.ExportSettings
-   Copyright   : © 2016–2018 Albert Krewinkel
+   Copyright   : © 2016–2019 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
diff --git a/src/Text/Pandoc/Readers/Org/Inlines.hs b/src/Text/Pandoc/Readers/Org/Inlines.hs
--- a/src/Text/Pandoc/Readers/Org/Inlines.hs
+++ b/src/Text/Pandoc/Readers/Org/Inlines.hs
@@ -1,26 +1,8 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2014-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-
-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.Org.Inlines
-   Copyright   : Copyright (C) 2014-2018 Albert Krewinkel
+   Copyright   : Copyright (C) 2014-2019 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
diff --git a/src/Text/Pandoc/Readers/Org/Meta.hs b/src/Text/Pandoc/Readers/Org/Meta.hs
--- a/src/Text/Pandoc/Readers/Org/Meta.hs
+++ b/src/Text/Pandoc/Readers/Org/Meta.hs
@@ -1,27 +1,9 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE FlexibleContexts #-}
 {-# LANGUAGE TupleSections    #-}
-{-
-Copyright (C) 2014-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-
-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.Org.Meta
-   Copyright   : Copyright (C) 2014-2018 Albert Krewinkel
+   Copyright   : Copyright (C) 2014-2019 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
diff --git a/src/Text/Pandoc/Readers/Org/ParserState.hs b/src/Text/Pandoc/Readers/Org/ParserState.hs
--- a/src/Text/Pandoc/Readers/Org/ParserState.hs
+++ b/src/Text/Pandoc/Readers/Org/ParserState.hs
@@ -1,27 +1,9 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE FlexibleInstances     #-}
 {-# LANGUAGE MultiParamTypeClasses #-}
-{-
-Copyright (C) 2014-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-
-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.Org.ParserState
-   Copyright   : Copyright (C) 2014-2018 Albert Krewinkel
+   Copyright   : Copyright (C) 2014-2019 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
diff --git a/src/Text/Pandoc/Readers/Org/Parsing.hs b/src/Text/Pandoc/Readers/Org/Parsing.hs
--- a/src/Text/Pandoc/Readers/Org/Parsing.hs
+++ b/src/Text/Pandoc/Readers/Org/Parsing.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2014-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-
-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.Org.Parsing
-   Copyright   : Copyright (C) 2014-2018 Albert Krewinkel
+   Copyright   : Copyright (C) 2014-2019 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
diff --git a/src/Text/Pandoc/Readers/Org/Shared.hs b/src/Text/Pandoc/Readers/Org/Shared.hs
--- a/src/Text/Pandoc/Readers/Org/Shared.hs
+++ b/src/Text/Pandoc/Readers/Org/Shared.hs
@@ -1,26 +1,8 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2014-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-
-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.Org.Shared
-   Copyright   : Copyright (C) 2014-2018 Albert Krewinkel
+   Copyright   : Copyright (C) 2014-2019 Albert Krewinkel
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
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
@@ -2,27 +2,9 @@
 {-# LANGUAGE FlexibleContexts    #-}
 {-# LANGUAGE OverloadedStrings   #-}
 {-# LANGUAGE ScopedTypeVariables #-}
-{-
-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.RST
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Readers/Roff.hs b/src/Text/Pandoc/Readers/Roff.hs
--- a/src/Text/Pandoc/Readers/Roff.hs
+++ b/src/Text/Pandoc/Readers/Roff.hs
@@ -1,28 +1,8 @@
 {-# LANGUAGE FlexibleContexts #-}
 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
-{-
-  Copyright (C) 2018 Yan Pashkovsky <yanp.bugz@gmail.com>
-                     and John MacFarlane
-
-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.Roff
-   Copyright   : Copyright (C) 2018 Yan Pashkovsky and John MacFarlane
+   Copyright   : Copyright (C) 2018-2019 Yan Pashkovsky and John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Yan Pashkovsky <yanp.bugz@gmail.com>
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,26 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE FlexibleContexts  #-}
 {-# LANGUAGE RelaxedPolyRec    #-}
-
 -- RelaxedPolyRec needed for inlinesBetween on GHC < 7
-{-
-  Copyright (C) 2014 Alexander Sulfrian <alexander.sulfrian@fu-berlin.de>
-
-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.TWiki
    Copyright   : Copyright (C) 2014 Alexander Sulfrian
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
@@ -1,27 +1,8 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2010-2012 Paul Rivier <paul*rivier#demotera*com> | tr '*#' '.@'
-              2010-2018 John MacFarlane
-
-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.Textile
    Copyright   : Copyright (C) 2010-2012 Paul Rivier
-                               2010-2018 John MacFarlane
+                               2010-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Paul Rivier <paul*rivier#demotera*com>
diff --git a/src/Text/Pandoc/Readers/Txt2Tags.hs b/src/Text/Pandoc/Readers/Txt2Tags.hs
--- a/src/Text/Pandoc/Readers/Txt2Tags.hs
+++ b/src/Text/Pandoc/Readers/Txt2Tags.hs
@@ -1,22 +1,4 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2014 Matthew Pickering <matthewtpickering@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.Txt2Tags
    Copyright   : Copyright (C) 2014 Matthew Pickering
diff --git a/src/Text/Pandoc/Readers/Vimwiki.hs b/src/Text/Pandoc/Readers/Vimwiki.hs
--- a/src/Text/Pandoc/Readers/Vimwiki.hs
+++ b/src/Text/Pandoc/Readers/Vimwiki.hs
@@ -1,26 +1,8 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE CPP #-}
-{-
-  Copyright (C) 2017-2018 Yuchen Pei <me@ypei.me>
-
-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.Vimwiki
-   Copyright   : Copyright (C) 2017-2018 Yuchen Pei
+   Copyright   : Copyright (C) 2017-2019 Yuchen Pei
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Yuchen Pei <me@ypei.me>
diff --git a/src/Text/Pandoc/RoffChar.hs b/src/Text/Pandoc/RoffChar.hs
--- a/src/Text/Pandoc/RoffChar.hs
+++ b/src/Text/Pandoc/RoffChar.hs
@@ -1,26 +1,8 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 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.RoffChar
-   Copyright   : Copyright (C) 2007-2018 John MacFarlane
+   Copyright   : Copyright (C) 2007-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/SelfContained.hs b/src/Text/Pandoc/SelfContained.hs
--- a/src/Text/Pandoc/SelfContained.hs
+++ b/src/Text/Pandoc/SelfContained.hs
@@ -1,26 +1,8 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2011-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.SelfContained
-   Copyright   : Copyright (C) 2011-2018 John MacFarlane
+   Copyright   : Copyright (C) 2011-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Shared.hs b/src/Text/Pandoc/Shared.hs
--- a/src/Text/Pandoc/Shared.hs
+++ b/src/Text/Pandoc/Shared.hs
@@ -3,32 +3,13 @@
 {-# LANGUAGE DeriveDataTypeable    #-}
 {-# LANGUAGE FlexibleContexts      #-}
 {-# LANGUAGE MultiParamTypeClasses #-}
-
 {-# LANGUAGE ScopedTypeVariables   #-}
 {-# LANGUAGE ViewPatterns          #-}
 {-# LANGUAGE FlexibleInstances  #-}
 {-# LANGUAGE TypeSynonymInstances  #-}
-{-
-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.Shared
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -86,6 +67,7 @@
                      eastAsianLineBreakFilter,
                      underlineSpan,
                      splitSentences,
+                     filterIpynbOutput,
                      -- * TagSoup HTML handling
                      renderTags',
                      -- * File handling
@@ -105,8 +87,8 @@
                      defaultBlocksSeparator,
                      -- * Safe read
                      safeRead,
-                     -- * Temp directory
-                     withTempDir,
+                     -- * User data directory
+                     defaultUserDataDirs,
                      -- * Version
                      pandocVersion
                     ) where
@@ -122,19 +104,19 @@
                   generalCategory, GeneralCategory(NonSpacingMark,
                   SpacingCombiningMark, EnclosingMark, ConnectorPunctuation))
 import Data.Data (Data, Typeable)
-import Data.List (find, intercalate, intersperse, stripPrefix)
+import Data.List (find, intercalate, intersperse, stripPrefix, sortBy)
 import qualified Data.Map as M
 import Data.Maybe (mapMaybe)
 import Data.Sequence (ViewL (..), ViewR (..), viewl, viewr)
 import qualified Data.Set as Set
 import qualified Data.Text as T
+import Data.Ord (comparing)
 import Data.Version (showVersion)
 import Network.URI (URI (uriScheme), escapeURIString, parseURI)
 import Paths_pandoc (version)
 import System.Directory
 import System.FilePath (isPathSeparator, splitDirectories)
 import qualified System.FilePath.Posix as Posix
-import System.IO.Temp
 import Text.HTML.TagSoup (RenderOptions (..), Tag (..), renderOptions,
                           renderTagsOptions)
 import Text.Pandoc.Builder (Blocks, Inlines, ToMetaValue (..))
@@ -416,20 +398,25 @@
         go x       = x
 
 -- | Change final list item from @Para@ to @Plain@ if the list contains
--- no other @Para@ blocks.  Like compactify, but operates on @Blocks@ rather
--- than @[Block]@.
+-- no other @Para@ blocks.  Otherwise (if the list items contain @Para@
+-- blocks besides possibly at the end), turn any @Plain@s into @Para@s (#5285).
 compactify :: [Blocks]  -- ^ List of list items (each a list of blocks)
            -> [Blocks]
 compactify [] = []
 compactify items =
   let (others, final) = (init items, last items)
   in  case reverse (B.toList final) of
-           (Para a:xs) -> case [Para x | Para x <- concatMap B.toList items] of
-                            -- if this is only Para, change to Plain
-                            [_] -> others ++ [B.fromList (reverse $ Plain a : xs)]
-                            _   -> items
-           _      -> items
+           (Para a:xs)
+             | null [Para x | Para x <- (xs ++ concatMap B.toList others)]
+             -> others ++ [B.fromList (reverse (Plain a : xs))]
+           _ | null [Para x | Para x <- concatMap B.toList items]
+             -> items
+           _ -> map (fmap plainToPara) items
 
+plainToPara :: Block -> Block
+plainToPara (Plain ils) = Para ils
+plainToPara x = x
+
 -- | Like @compactify@, but acts on items of definition lists.
 compactifyDL :: [(Inlines, [Blocks])] -> [(Inlines, [Blocks])]
 compactifyDL items =
@@ -684,6 +671,31 @@
   let (sent, rest) = breakSentence xs
   in  if null rest then [sent] else sent : splitSentences rest
 
+-- | Process ipynb output cells.  If mode is Nothing,
+-- remove all output.  If mode is Just format, select
+-- best output for the format.
+filterIpynbOutput :: Maybe Format -> Pandoc -> Pandoc
+filterIpynbOutput mode = walk go
+  where go (Div (ident, ("output":os), kvs) bs) =
+          case mode of
+            Nothing  -> Div (ident, ("output":os), kvs) []
+            Just fmt -> Div (ident, ("output":os), kvs) $
+              take 1 $ sortBy (comparing rank) bs
+                where
+                  rank (RawBlock (Format "html") _)
+                    | fmt == Format "html" = (1 :: Int)
+                    | fmt == Format "markdown" = 2
+                    | otherwise = 3
+                  rank (RawBlock (Format "latex") _)
+                    | fmt == Format "latex" = 1
+                    | fmt == Format "markdown" = 2
+                    | otherwise = 3
+                  rank (RawBlock f _)
+                    | fmt == f = 1
+                    | otherwise = 3
+                  rank _ = 2
+        go x = x
+
 --
 -- TagSoup HTML handling
 --
@@ -884,13 +896,16 @@
                   _                 -> mzero
 
 --
--- Temp directory
+-- User data directory
 --
 
-withTempDir :: String -> (FilePath -> IO a) -> IO a
-withTempDir =
-#ifdef _WINDOWS
-  withTempDirectory "."
-#else
-  withSystemTempDirectory
-#endif
+-- | Return appropriate user data directory for platform.  We use
+-- XDG_DATA_HOME (or its default value), but fall back to the
+-- legacy user data directory ($HOME/.pandoc on *nix) if this is
+-- missing.
+defaultUserDataDirs :: IO [FilePath]
+defaultUserDataDirs = E.catch (do
+  xdgDir <- getXdgDirectory XdgData "pandoc"
+  legacyDir <- getAppUserDataDirectory "pandoc"
+  return $ ordNub [xdgDir, legacyDir])
+ (\(_ :: E.SomeException) -> return [])
diff --git a/src/Text/Pandoc/Slides.hs b/src/Text/Pandoc/Slides.hs
--- a/src/Text/Pandoc/Slides.hs
+++ b/src/Text/Pandoc/Slides.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2012-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.Slides
-   Copyright   : Copyright (C) 2012-2018 John MacFarlane
+   Copyright   : Copyright (C) 2012-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
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,25 +1,7 @@
 {-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2009-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.Templates
-   Copyright   : Copyright (C) 2009-2018 John MacFarlane
+   Copyright   : Copyright (C) 2009-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Translations.hs b/src/Text/Pandoc/Translations.hs
--- a/src/Text/Pandoc/Translations.hs
+++ b/src/Text/Pandoc/Translations.hs
@@ -2,27 +2,9 @@
 {-# LANGUAGE CPP                        #-}
 {-# LANGUAGE DeriveGeneric              #-}
 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
-{-
-Copyright (C) 2017-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.Translations
-   Copyright   : Copyright (C) 2017-2018 John MacFarlane
+   Copyright   : Copyright (C) 2017-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -59,28 +41,28 @@
 import qualified Text.Pandoc.UTF8 as UTF8
 
 data Term =
-    Preface
-  | References
-  | Abstract
+    Abstract
+  | Appendix
   | Bibliography
+  | Cc
   | Chapter
-  | Appendix
   | Contents
+  | Encl
+  | Figure
+  | Glossary
+  | Index
+  | Listing
   | ListOfFigures
   | ListOfTables
-  | Index
-  | Figure
-  | Table
-  | Part
   | Page
+  | Part
+  | Preface
+  | Proof
+  | References
   | See
   | SeeAlso
-  | Encl
-  | Cc
+  | Table
   | To
-  | Proof
-  | Glossary
-  | Listing
   deriving (Show, Eq, Ord, Generic, Enum, Read)
 
 newtype Translations = Translations (M.Map Term String)
diff --git a/src/Text/Pandoc/UTF8.hs b/src/Text/Pandoc/UTF8.hs
--- a/src/Text/Pandoc/UTF8.hs
+++ b/src/Text/Pandoc/UTF8.hs
@@ -1,26 +1,8 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2010-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.UTF8
-   Copyright   : Copyright (C) 2010-2018 John MacFarlane
+   Copyright   : Copyright (C) 2010-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/UUID.hs b/src/Text/Pandoc/UUID.hs
--- a/src/Text/Pandoc/UUID.hs
+++ b/src/Text/Pandoc/UUID.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2010-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.UUID
-   Copyright   : Copyright (C) 2010-2018 John MacFarlane
+   Copyright   : Copyright (C) 2010-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Writers.hs b/src/Text/Pandoc/Writers.hs
--- a/src/Text/Pandoc/Writers.hs
+++ b/src/Text/Pandoc/Writers.hs
@@ -1,28 +1,10 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-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
--}
 {-# LANGUAGE FlexibleInstances   #-}
 {-# LANGUAGE GADTs               #-}
 {-# LANGUAGE ScopedTypeVariables #-}
-
 {- |
    Module      : Text.Pandoc
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -37,6 +19,7 @@
       Writer(..)
     , writers
     , writeAsciiDoc
+    , writeAsciiDoctor
     , writeBeamer
     , writeCommonMark
     , writeConTeXt
@@ -178,6 +161,7 @@
   ,("rtf"          , TextWriter writeRTF)
   ,("org"          , TextWriter writeOrg)
   ,("asciidoc"     , TextWriter writeAsciiDoc)
+  ,("asciidoctor"  , TextWriter writeAsciiDoctor)
   ,("haddock"      , TextWriter writeHaddock)
   ,("commonmark"   , TextWriter writeCommonMark)
   ,("gfm"          , TextWriter writeCommonMark)
diff --git a/src/Text/Pandoc/Writers/AsciiDoc.hs b/src/Text/Pandoc/Writers/AsciiDoc.hs
--- a/src/Text/Pandoc/Writers/AsciiDoc.hs
+++ b/src/Text/Pandoc/Writers/AsciiDoc.hs
@@ -1,26 +1,8 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
-{-
-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.Writers.AsciiDoc
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -37,7 +19,7 @@
 
 AsciiDoc:  <http://www.methods.co.nz/asciidoc/>
 -}
-module Text.Pandoc.Writers.AsciiDoc (writeAsciiDoc) where
+module Text.Pandoc.Writers.AsciiDoc (writeAsciiDoc, writeAsciiDoctor) where
 import Prelude
 import Control.Monad.State.Strict
 import Data.Char (isPunctuation, isSpace, toLower)
@@ -56,24 +38,37 @@
 import Text.Pandoc.Templates (renderTemplate')
 import Text.Pandoc.Writers.Shared
 
-data WriterState = WriterState { defListMarker    :: String
-                               , orderedListLevel :: Int
-                               , bulletListLevel  :: Int
-                               , intraword        :: Bool
-                               , autoIds          :: Set.Set String
+data WriterState = WriterState { defListMarker       :: String
+                               , orderedListLevel    :: Int
+                               , bulletListLevel     :: Int
+                               , intraword           :: Bool
+                               , autoIds             :: Set.Set String
+                               , asciidoctorVariant  :: Bool
+                               , inList              :: Bool
+                               , hasMath             :: Bool
                                }
 
+defaultWriterState :: WriterState
+defaultWriterState = WriterState { defListMarker      = "::"
+                                 , orderedListLevel   = 0
+                                 , bulletListLevel    = 0
+                                 , intraword          = False
+                                 , autoIds            = Set.empty
+                                 , asciidoctorVariant = False
+                                 , inList             = False
+                                 , hasMath            = False
+                                 }
+
 -- | Convert Pandoc to AsciiDoc.
 writeAsciiDoc :: PandocMonad m => WriterOptions -> Pandoc -> m Text
 writeAsciiDoc opts document =
-  evalStateT (pandocToAsciiDoc opts document) WriterState{
-      defListMarker = "::"
-    , orderedListLevel = 1
-    , bulletListLevel = 1
-    , intraword = False
-    , autoIds = Set.empty
-    }
+  evalStateT (pandocToAsciiDoc opts document) defaultWriterState
 
+-- | Convert Pandoc to AsciiDoctor compatible AsciiDoc.
+writeAsciiDoctor :: PandocMonad m => WriterOptions -> Pandoc -> m Text
+writeAsciiDoctor opts document =
+  evalStateT (pandocToAsciiDoc opts document) defaultWriterState{ asciidoctorVariant = True }
+
 type ADW = StateT WriterState
 
 -- | Return asciidoc representation of document.
@@ -92,11 +87,13 @@
               meta
   body <- vcat <$> mapM (elementToAsciiDoc 1 opts) (hierarchicalize blocks)
   let main = render colwidth body
+  st <- get
   let context  = defField "body" main
                $ defField "toc"
                   (writerTableOfContents opts &&
                    isJust (writerTemplate opts))
-               $defField "titleblock" titleblock metadata
+               $ defField "math" (hasMath st)
+               $ defField "titleblock" titleblock metadata
   case writerTemplate opts of
        Nothing  -> return main
        Just tpl -> renderTemplate' tpl context
@@ -255,7 +252,10 @@
   return $
     caption'' $$ tablespec $$ border $$ head'' $$ body $$ border $$ blankline
 blockToAsciiDoc opts (BulletList items) = do
+  inlist <- gets inList
+  modify $ \st -> st{ inList = True }
   contents <- mapM (bulletListItemToAsciiDoc opts) items
+  modify $ \st -> st{ inList = inlist }
   return $ cat contents <> blankline
 blockToAsciiDoc opts (OrderedList (start, sty, _delim) items) = do
   let listStyle = case sty of
@@ -267,10 +267,16 @@
   let listoptions = case intercalate ", " (listStyle ++ listStart) of
                           [] -> empty
                           x  -> brackets (text x)
+  inlist <- gets inList
+  modify $ \st -> st{ inList = True }
   contents <- mapM (orderedListItemToAsciiDoc opts) items
+  modify $ \st -> st{ inList = inlist }
   return $ listoptions $$ cat contents <> blankline
 blockToAsciiDoc opts (DefinitionList items) = do
+  inlist <- gets inList
+  modify $ \st -> st{ inList = True }
   contents <- mapM (definitionListItemToAsciiDoc opts) items
+  modify $ \st -> st{ inList = inlist }
   return $ cat contents <> blankline
 blockToAsciiDoc opts (Div (ident,_,_) bs) = do
   let identifier = if null ident then empty else "[[" <> text ident <> "]]"
@@ -285,18 +291,33 @@
   modify $ \s -> s{ bulletListLevel = lev + 1 }
   contents <- foldM (addBlock opts) empty blocks
   modify $ \s -> s{ bulletListLevel = lev }
-  let marker = text (replicate lev '*')
-  return $ marker <> text " " <> contents <> cr
+  let marker = text (replicate (lev + 1) '*')
+  return $ marker <> text " " <> listBegin blocks <>
+    contents <> cr
 
 addBlock :: PandocMonad m => WriterOptions -> Doc -> Block -> ADW m Doc
-addBlock opts d b | isEmpty d    = chomp `fmap` blockToAsciiDoc opts b
-addBlock opts d b@(BulletList _) = do x <- blockToAsciiDoc opts b
-                                      return $ d <> cr <> chomp x
-addBlock opts d b@(OrderedList _ _) = do x <- blockToAsciiDoc opts b
-                                         return $ d <> cr <> chomp x
-addBlock opts d b = do x <- blockToAsciiDoc opts b
-                       return $ d <> cr <> text "+" <> cr <> chomp x
+addBlock opts d b = do
+  x <- chomp <$> blockToAsciiDoc opts b
+  return $
+    case b of
+        BulletList{} -> d <> cr <> x
+        OrderedList{} -> d <> cr <> x
+        Para (Math DisplayMath _:_) -> d <> cr <> x
+        Plain (Math DisplayMath _:_) -> d <> cr <> x
+        Para{} | isEmpty d -> x
+        Plain{} | isEmpty d -> x
+        _ -> d <> cr <> text "+" <> cr <> x
 
+listBegin :: [Block] -> Doc
+listBegin blocks =
+        case blocks of
+          Para (Math DisplayMath _:_) : _  -> "{blank}"
+          Plain (Math DisplayMath _:_) : _ -> "{blank}"
+          Para _ : _                       -> empty
+          Plain _ : _                      -> empty
+          _ : _                            -> "{blank}"
+          []                               -> "{blank}"
+
 -- | Convert ordered list item (a list of blocks) to asciidoc.
 orderedListItemToAsciiDoc :: PandocMonad m
                           => WriterOptions -- ^ options
@@ -307,8 +328,8 @@
   modify $ \s -> s{ orderedListLevel = lev + 1 }
   contents <- foldM (addBlock opts) empty blocks
   modify $ \s -> s{ orderedListLevel = lev }
-  let marker = text (replicate lev '.')
-  return $ marker <> text " " <> contents <> cr
+  let marker = text (replicate (lev + 1) '.')
+  return $ marker <> text " " <> listBegin blocks <> contents <> cr
 
 -- | Convert definition list item (label, list of blocks) to asciidoc.
 definitionListItemToAsciiDoc :: PandocMonad m
@@ -411,10 +432,26 @@
 inlineToAsciiDoc _ (Code _ str) = return $
   text "`" <> text (escapeStringUsing (backslashEscapes "`") str) <> "`"
 inlineToAsciiDoc _ (Str str) = return $ text $ escapeString str
-inlineToAsciiDoc _ (Math InlineMath str) =
-  return $ "latexmath:[$" <> text str <> "$]"
-inlineToAsciiDoc _ (Math DisplayMath str) =
-  return $ "latexmath:[\\[" <> text str <> "\\]]"
+inlineToAsciiDoc _ (Math InlineMath str) = do
+  isAsciidoctor <- gets asciidoctorVariant
+  modify $ \st -> st{ hasMath = True }
+  let content = if isAsciidoctor
+                then text str
+                else "$" <> text str <> "$"
+  return $ "latexmath:[" <> content <> "]"
+inlineToAsciiDoc _ (Math DisplayMath str) = do
+  isAsciidoctor <- gets asciidoctorVariant
+  modify $ \st -> st{ hasMath = True }
+  let content = if isAsciidoctor
+                then text str
+                else "\\[" <> text str <> "\\]"
+  inlist <- gets inList
+  let sepline = if inlist
+                   then text "+"
+                   else blankline
+  return $
+      (cr <> sepline) $$ "[latexmath]" $$ "++++" $$
+      content $$ "++++" <> cr
 inlineToAsciiDoc _ il@(RawInline f s)
   | f == "asciidoc" = return $ text s
   | otherwise         = do
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
@@ -1,26 +1,8 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2015-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.Writers.CommonMark
-   Copyright   : Copyright (C) 2015-2018 John MacFarlane
+   Copyright   : Copyright (C) 2015-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Writers/ConTeXt.hs b/src/Text/Pandoc/Writers/ConTeXt.hs
--- a/src/Text/Pandoc/Writers/ConTeXt.hs
+++ b/src/Text/Pandoc/Writers/ConTeXt.hs
@@ -1,27 +1,9 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings   #-}
 {-# LANGUAGE ScopedTypeVariables #-}
-{-
-Copyright (C) 2007-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.Writers.ConTeXt
-   Copyright   : Copyright (C) 2007-2018 John MacFarlane
+   Copyright   : Copyright (C) 2007-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Writers/Custom.hs b/src/Text/Pandoc/Writers/Custom.hs
--- a/src/Text/Pandoc/Writers/Custom.hs
+++ b/src/Text/Pandoc/Writers/Custom.hs
@@ -1,25 +1,8 @@
 {-# LANGUAGE FlexibleInstances  #-}
 {-# LANGUAGE NoImplicitPrelude  #-}
-{- Copyright (C) 2012-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.Writers.Custom
-   Copyright   : Copyright (C) 2012-2018 John MacFarlane
+   Copyright   : Copyright (C) 2012-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Writers/Docbook.hs b/src/Text/Pandoc/Writers/Docbook.hs
--- a/src/Text/Pandoc/Writers/Docbook.hs
+++ b/src/Text/Pandoc/Writers/Docbook.hs
@@ -1,27 +1,9 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE PatternGuards     #-}
-{-
-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.Writers.Docbook
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Writers/Docx.hs b/src/Text/Pandoc/Writers/Docx.hs
--- a/src/Text/Pandoc/Writers/Docx.hs
+++ b/src/Text/Pandoc/Writers/Docx.hs
@@ -3,27 +3,9 @@
 {-# LANGUAGE RankNTypes          #-}
 {-# LANGUAGE ScopedTypeVariables #-}
 {-# LANGUAGE ViewPatterns        #-}
-{-
-Copyright (C) 2012-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.Writers.Docx
-   Copyright   : Copyright (C) 2012-2018 John MacFarlane
+   Copyright   : Copyright (C) 2012-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Writers/DokuWiki.hs b/src/Text/Pandoc/Writers/DokuWiki.hs
--- a/src/Text/Pandoc/Writers/DokuWiki.hs
+++ b/src/Text/Pandoc/Writers/DokuWiki.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2008-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.Writers.DokuWiki
-   Copyright   : Copyright (C) 2008-2018 John MacFarlane
+   Copyright   : Copyright (C) 2008-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Clare Macrae <clare.macrae@googlemail.com>
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
@@ -3,27 +3,9 @@
 {-# LANGUAGE FlexibleContexts    #-}
 {-# LANGUAGE PatternGuards       #-}
 {-# LANGUAGE ScopedTypeVariables #-}
-{-
-Copyright (C) 2010-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.Writers.EPUB
-   Copyright   : Copyright (C) 2010-2018 John MacFarlane
+   Copyright   : Copyright (C) 2010-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
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
@@ -1,29 +1,9 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE PatternGuards #-}
-
-{-
-Copyright (c) 2011-2012 Sergey Astanin
-              2012-2018 John MacFarlane
-
-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.Writers.FB2
 Copyright   : Copyright (C) 2011-2012 Sergey Astanin
-                            2012-2018 John MacFarlane
+                            2012-2019 John MacFarlane
 License     : GNU GPL, version 2 or above
 
 Maintainer  : John MacFarlane
@@ -52,13 +32,15 @@
 import Text.XML.Light
 import qualified Text.XML.Light as X
 import qualified Text.XML.Light.Cursor as XC
+import qualified Text.XML.Light.Input as XI
 
 import Text.Pandoc.Class (PandocMonad, report)
 import qualified Text.Pandoc.Class as P
 import Text.Pandoc.Definition
 import Text.Pandoc.Logging
 import Text.Pandoc.Options (HTMLMathMethod (..), WriterOptions (..), def)
-import Text.Pandoc.Shared (capitalize, isHeaderBlock, isURI, orderedListMarkers)
+import Text.Pandoc.Shared (capitalize, isURI, orderedListMarkers, hierarchicalize)
+import qualified Text.Pandoc.Shared as Shared (Element(Blk, Sec))
 
 -- | Data to be written at the end of the document:
 -- (foot)notes, URLs, references, images.
@@ -177,20 +159,28 @@
 -- representation.
 renderSections :: PandocMonad m => Int -> [Block] -> FBM m [Content]
 renderSections level blocks = do
-    let secs = splitSections level blocks
-    mapM (renderSection level) secs
+    let elements = hierarchicalize blocks
+    let isSection Shared.Sec{} = True
+        isSection _ = False
+    let (initialBlocks, secs) = break isSection elements
+    let elements' = if null initialBlocks
+        then secs
+        else Shared.Sec 1 [] nullAttr mempty initialBlocks : secs
+    cMapM (renderSection level) elements'
 
-renderSection :: PandocMonad m => Int -> ([Inline], [Block]) -> FBM m Content
-renderSection level (ttl, body) = do
-    title <- if null ttl
+
+
+renderSection :: PandocMonad m =>  Int -> Shared.Element -> FBM m [Content]
+renderSection _   (Shared.Blk block) = blockToXml block
+renderSection lvl (Shared.Sec _ _num (id',_,_) title elements) = do
+  content <- cMapM (renderSection (lvl + 1)) elements
+  title' <- if null title
             then return []
-            else list . el "title" <$> formatTitle ttl
-    content <- if hasSubsections body
-               then renderSections (level + 1) body
-               else cMapM blockToXml body
-    return $ el "section" (title ++ content)
-  where
-    hasSubsections = any isHeaderBlock
+            else list . el "title" <$> formatTitle title
+  let sectionContent = if null id'
+      then el "section" (title' ++ content)
+      else el "section" ([uattr "id" id'], (title' ++ content))
+  return $ [sectionContent]
 
 -- | Only <p> and <empty-line> are allowed within <title> in FB2.
 formatTitle :: PandocMonad m => [Inline] -> FBM m [Content]
@@ -206,24 +196,6 @@
 isLineBreak LineBreak = True
 isLineBreak _         = False
 
--- | Divide the stream of block elements into sections: [(title, blocks)].
-splitSections :: Int -> [Block] -> [([Inline], [Block])]
-splitSections level blocks = reverse $ revSplit (reverse blocks)
-  where
-  revSplit [] = []
-  revSplit rblocks =
-    let (lastsec, before) = break sameLevel rblocks
-        (header, prevblocks) =
-            case before of
-              (Header n _ title:prevblocks') ->
-                  if n == level
-                     then (title, prevblocks')
-                     else ([], before)
-              _ -> ([], before)
-    in (header, reverse lastsec) : revSplit prevblocks
-  sameLevel (Header n _ _) = n == level
-  sameLevel _              = False
-
 -- | Make another FictionBook body with footnotes.
 renderFootnotes :: PandocMonad m => FBM m [Content]
 renderFootnotes = do
@@ -325,9 +297,10 @@
 blockToXml (Para ss) = (list . el "p") <$> cMapM toXml ss
 blockToXml (CodeBlock _ s) = return . spaceBeforeAfter .
                              map (el "p" . el "code") . lines $ s
-blockToXml b@(RawBlock _ _) = do
-  report $ BlockNotRendered b
-  return []
+blockToXml (RawBlock f str) = do
+  if f == Format "fb2"
+    then return $ XI.parseXML str
+    else return []
 blockToXml (Div _ bs) = cMapM blockToXml bs
 blockToXml (BlockQuote bs) = (list . el "cite") <$> cMapM blockToXml bs
 blockToXml (LineBlock lns) =
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
@@ -4,27 +4,9 @@
 {-# LANGUAGE ScopedTypeVariables #-}
 {-# LANGUAGE ViewPatterns        #-}
 {-# LANGUAGE MultiWayIf          #-}
-{-
-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.Writers.HTML
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -473,13 +455,16 @@
   let inDiv xs = Blk (RawBlock (Format "html") ("<div class=\""
                        ++ fragmentClass ++ "\">")) :
                    (xs ++ [Blk (RawBlock (Format "html") "</div>")])
-  innerContents <- mapM (elementToHtml (Just level) slideLevel opts)
-                   $ if titleSlide
+  let (titleBlocks, innerSecs) =
+                     if titleSlide
                         -- title slides have no content of their own
-                        then filter isSec elements
+                        then ([x | Blk x <- elements],
+                              filter isSec elements)
                         else case splitBy isPause elements of
-                                  []     -> []
-                                  (x:xs) -> x ++ concatMap inDiv xs
+                                  []     -> ([],[])
+                                  (x:xs) -> ([],x ++ concatMap inDiv xs)
+  titleContents <- blockListToHtml opts titleBlocks
+  innerContents <- mapM (elementToHtml (Just level) slideLevel opts) innerSecs
   let inNl x = mconcat $ nl opts : intersperse (nl opts) x ++ [nl opts]
   let classes' = ["title-slide" | titleSlide] ++ ["slide" | slide] ++
                   ["section" | (slide || writerSectionDivs opts) &&
@@ -492,8 +477,7 @@
   let attr = (id',classes',keyvals)
   if titleSlide
      then do
-       t <- addAttrs opts attr $
-                   secttag header'
+       t <- addAttrs opts attr $ secttag $ header' <> titleContents
        return $
          (if slideVariant == RevealJsSlides && not (null innerContents)
              -- revealjs doesn't like more than one level of section nesting:
@@ -521,7 +505,9 @@
         , epubVersion == Just EPUB3
                 = H5.section ! A.class_ "footnotes"
                              ! customAttribute "epub:type" "footnotes" $ x
-        | html5 = H5.section ! A.class_ "footnotes" $ x
+        | html5 = H5.section ! A.class_ "footnotes"
+                             ! customAttribute "role" "doc-endnotes"
+                             $ x
         | slideVariant /= NoSlides = H.div ! A.class_ "footnotes slide" $ x
         | otherwise = H.div ! A.class_ "footnotes" $ x
   return $
@@ -729,7 +715,10 @@
   slideVariant <- gets stSlideVariant
   let kvs = [(k,v) | (k,v) <- kvs', k /= "width"] ++
             [("style", "width:" ++ w ++ ";")
-             | ("width",w) <- kvs', "column" `elem` classes]
+             | ("width",w) <- kvs', "column" `elem` classes] ++
+            [("role", "doc-bibliography") | ident == "refs" && html5] ++
+            [("role", "doc-biblioentry")
+              | "ref-item" `isPrefixOf` ident && html5]
   let speakerNotes = "notes" `elem` classes
   -- we don't want incremental output inside speaker notes, see #1394
   let opts' = if | speakerNotes -> opts{ writerIncremental = False }
@@ -1183,20 +1172,32 @@
                                        $ toHtml ref
                         return $ case epubVersion of
                                       Just EPUB3 -> link ! customAttribute "epub:type" "noteref"
+                                      _ | html5  -> link ! H5.customAttribute
+                                                      "role" "doc-noteref"
                                       _          -> link
-    (Cite cits il)-> do contents <- inlineListToHtml opts il
+    (Cite cits il)-> do contents <- inlineListToHtml opts (walk addRoleToLink il)
                         let citationIds = unwords $ map citationId cits
                         let result = H.span ! A.class_ "citation" $ contents
                         return $ if html5
                                     then result ! customAttribute "data-cites" (toValue citationIds)
                                     else result
 
-blockListToNote :: PandocMonad m => WriterOptions -> String -> [Block] -> StateT WriterState m Html
-blockListToNote opts ref blocks =
+addRoleToLink :: Inline -> Inline
+addRoleToLink (Link (id',classes,kvs) ils (src,tit)) =
+  Link (id',classes,("role","doc-biblioref"):kvs) ils (src,tit)
+addRoleToLink x = x
+
+blockListToNote :: PandocMonad m
+                => WriterOptions -> String -> [Block]
+                -> StateT WriterState m Html
+blockListToNote opts ref blocks = do
+  html5 <- gets stHtml5
   -- If last block is Para or Plain, include the backlink at the end of
   -- that block. Otherwise, insert a new Plain block with the backlink.
-  let backlink = [Link ("",["footnote-back"],[]) [Str "↩"] ("#" ++ "fnref" ++ ref,[])]
-      blocks'  = if null blocks
+  let kvs = if html5 then [("role","doc-backlink")] else []
+  let backlink = [Link ("",["footnote-back"],kvs)
+                    [Str "↩"] ("#" ++ "fnref" ++ ref,[])]
+  let blocks'  = if null blocks
                     then []
                     else let lastBlock   = last blocks
                              otherBlocks = init blocks
@@ -1207,13 +1208,16 @@
                                                  [Plain (lst ++ backlink)]
                                   _           -> otherBlocks ++ [lastBlock,
                                                  Plain backlink]
-  in  do contents <- blockListToHtml opts blocks'
-         let noteItem = H.li ! prefixedId opts ("fn" ++ ref) $ contents
-         epubVersion <- gets stEPUBVersion
-         let noteItem' = case epubVersion of
-                              Just EPUB3 -> noteItem ! customAttribute "epub:type" "footnote"
-                              _          -> noteItem
-         return $ nl opts >> noteItem'
+  contents <- blockListToHtml opts blocks'
+  let noteItem = H.li ! prefixedId opts ("fn" ++ ref) $ contents
+  epubVersion <- gets stEPUBVersion
+  let noteItem' = case epubVersion of
+                       Just EPUB3 -> noteItem !
+                                       customAttribute "epub:type" "footnote"
+                       _ | html5  -> noteItem !
+                                       customAttribute "role" "doc-endnote"
+                       _          -> noteItem
+  return $ nl opts >> noteItem'
 
 isMathEnvironment :: String -> Bool
 isMathEnvironment s = "\\begin{" `isPrefixOf` s &&
@@ -1434,6 +1438,7 @@
   , "rel"
   , "required"
   , "reversed"
+  , "role"
   , "rows"
   , "rowspan"
   , "sandbox"
diff --git a/src/Text/Pandoc/Writers/Haddock.hs b/src/Text/Pandoc/Writers/Haddock.hs
--- a/src/Text/Pandoc/Writers/Haddock.hs
+++ b/src/Text/Pandoc/Writers/Haddock.hs
@@ -1,25 +1,6 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings   #-}
 {-# LANGUAGE ScopedTypeVariables #-}
-
-{-
-Copyright (C) 2014-2015, 2017-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.Writers.Haddock
    Copyright   : Copyright (C) 2014-2015,2017 John MacFarlane
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
@@ -5,7 +5,7 @@
 
 {- |
    Module      : Text.Pandoc.Writers.ICML
-   Copyright   : Copyright (C) 2013-2018 github.com/mb21
+   Copyright   : Copyright (C) 2013-2019 github.com/mb21
    License     : GNU GPL, version 2 or above
 
    Stability   : alpha
diff --git a/src/Text/Pandoc/Writers/Ipynb.hs b/src/Text/Pandoc/Writers/Ipynb.hs
--- a/src/Text/Pandoc/Writers/Ipynb.hs
+++ b/src/Text/Pandoc/Writers/Ipynb.hs
@@ -2,24 +2,6 @@
 {-# LANGUAGE DeriveGeneric #-}
 {-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE ScopedTypeVariables #-}
-{-
-Copyright (C) 2019 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.Writers.Ipynb
    Copyright   : Copyright (C) 2019 John MacFarlane
@@ -49,7 +31,7 @@
 import qualified Data.Text as T
 import Data.Aeson as Aeson
 import qualified Text.Pandoc.UTF8 as UTF8
-import Text.Pandoc.Shared (safeRead)
+import Text.Pandoc.Shared (safeRead, isURI)
 import Text.Pandoc.Writers.Shared (metaToJSON')
 import Text.Pandoc.Writers.Markdown (writeMarkdown)
 import qualified Data.Text.Encoding as TE
@@ -62,6 +44,7 @@
   notebook <- pandocToNotebook opts d
   return $ TE.decodeUtf8 . BL.toStrict . encodePretty' defConfig{
              confIndent  = Spaces 1,
+             confTrailingNewline = True,
              confCompare = keyOrder
                [ "cells", "nbformat", "nbformat_minor",
                  "cell_type", "output_type",
@@ -80,7 +63,7 @@
   let jupyterMeta =
         case lookupMeta "jupyter" meta of
           Just (MetaMap m) -> (Meta m <> B.deleteMeta "jupyter" meta)
-          _ -> meta
+          _ -> mempty
   metadata' <- metaToJSON' blockWriter inlineWriter $
                  B.deleteMeta "nbformat" $
                  B.deleteMeta "nbformat_minor" $ jupyterMeta
@@ -97,7 +80,8 @@
 addAttachment :: PandocMonad m
               => Inline
               -> StateT (M.Map Text MimeBundle) m Inline
-addAttachment (Image attr lab (src,tit)) = do
+addAttachment (Image attr lab (src,tit))
+  | not (isURI src) = do
   (img, mbmt) <- fetchItem src
   let mt = maybe "application/octet-stream" (T.pack) mbmt
   modify $ M.insert (T.pack src)
diff --git a/src/Text/Pandoc/Writers/JATS.hs b/src/Text/Pandoc/Writers/JATS.hs
--- a/src/Text/Pandoc/Writers/JATS.hs
+++ b/src/Text/Pandoc/Writers/JATS.hs
@@ -1,26 +1,8 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
-
-{-
-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.Writers.JATS
-   Copyright   : Copyright (C) 2017-2018 John MacFarlane
+   Copyright   : Copyright (C) 2017-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -230,7 +212,7 @@
   let (maintype, subtype) = imageMimeType src kvs
   let capt = if null txt
                 then empty
-                else inTagsSimple "caption" alt
+                else inTagsSimple "caption" $ inTagsSimple "p" alt
   let attr = [("id", ident) | not (null ident)] ++
              [(k,v) | (k,v) <- kvs, k `elem` ["fig-type", "orientation",
                                               "position", "specific-use"]]
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
@@ -2,27 +2,9 @@
 {-# LANGUAGE OverloadedStrings   #-}
 {-# LANGUAGE PatternGuards       #-}
 {-# LANGUAGE ScopedTypeVariables #-}
-{-
-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.Writers.LaTeX
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -39,8 +21,8 @@
 import Control.Applicative ((<|>))
 import Control.Monad.State.Strict
 import Data.Aeson (FromJSON, object, (.=))
-import Data.Char (isAlphaNum, isAscii, isDigit, isLetter, isPunctuation, ord,
-                  toLower)
+import Data.Char (isAlphaNum, isAscii, isDigit, isLetter, isSpace,
+                  isPunctuation, ord, toLower)
 import Data.List (foldl', intercalate, intersperse, isInfixOf, nubBy,
                   stripPrefix, (\\), uncons)
 import Data.Maybe (catMaybes, fromMaybe, isJust, mapMaybe, isNothing)
@@ -322,33 +304,42 @@
 stringToLaTeX :: PandocMonad m => StringContext -> String -> LW m String
 stringToLaTeX context zs = do
   opts <- gets stOptions
-  go opts context $
+  return $
+    foldr (go opts context) mempty $
     if writerPreferAscii opts
        then T.unpack $ Normalize.normalize Normalize.NFD $ T.pack zs
        else zs
  where
-  go  _ _     []     = return ""
-  go  opts ctx (x:xs) = do
+  go opts ctx x xs   =
     let ligatures = isEnabled Ext_smart opts && ctx == TextString
-    let isUrl = ctx == URLString
-    let mbAccentCmd =
+        isUrl = ctx == URLString
+        mbAccentCmd =
           if writerPreferAscii opts && ctx == TextString
              then uncons xs >>= \(c,_) -> M.lookup c accents
              else Nothing
-    let emits s =
+        emits s =
           case mbAccentCmd of
-               Just cmd -> ((cmd ++ "{" ++ s ++ "}") ++)
-                        <$> go opts ctx (drop 1 xs) -- drop combining accent
-               Nothing  -> (s++) <$> go opts ctx xs
-    let emitc c =
+               Just cmd ->
+                 cmd ++ "{" ++ s ++ "}" ++ drop 1 xs -- drop combining accent
+               Nothing  -> s ++ xs
+        emitc c =
           case mbAccentCmd of
-               Just cmd -> ((cmd ++ "{" ++ [c] ++ "}") ++)
-                        <$> go opts ctx (drop 1 xs) -- drop combining accent
-               Nothing  -> (c:) <$> go opts ctx xs
-    case x of
+               Just cmd ->
+                 cmd ++ "{" ++ [c] ++ "}" ++ drop 1 xs -- drop combining accent
+               Nothing  -> c : xs
+        emitcseq cs = do
+          case xs of
+            c:_ | isLetter c
+                , ctx == TextString
+                             -> cs <> " " <> xs
+                | isSpace c  -> cs <> "{}" <> xs
+                | ctx == TextString
+                             -> cs <> xs
+            _ -> cs <> "{}" <> xs
+    in case x of
          '{' -> emits "\\{"
          '}' -> emits "\\}"
-         '`' | ctx == CodeString -> emits "\\textasciigrave{}"
+         '`' | ctx == CodeString -> emitcseq "\\textasciigrave"
          '$' | not isUrl -> emits "\\$"
          '%' -> emits "\\%"
          '&' -> emits "\\&"
@@ -358,19 +349,19 @@
                      -- prevent adjacent hyphens from forming ligatures
                      ('-':_) -> emits "-\\/"
                      _       -> emitc '-'
-         '~' | not isUrl -> emits "\\textasciitilde{}"
+         '~' | not isUrl -> emitcseq "\\textasciitilde"
          '^' -> emits "\\^{}"
          '\\'| isUrl     -> emitc '/' -- NB. / works as path sep even on Windows
-             | otherwise -> emits "\\textbackslash{}"
-         '|' | not isUrl -> emits "\\textbar{}"
-         '<' -> emits "\\textless{}"
-         '>' -> emits "\\textgreater{}"
+             | otherwise -> emitcseq "\\textbackslash"
+         '|' | not isUrl -> emitcseq "\\textbar"
+         '<' -> emitcseq "\\textless"
+         '>' -> emitcseq "\\textgreater"
          '[' -> emits "{[}"  -- to avoid interpretation as
          ']' -> emits "{]}"  -- optional arguments
-         '\'' | ctx == CodeString -> emits "\\textquotesingle{}"
+         '\'' | ctx == CodeString -> emitcseq "\\textquotesingle"
          '\160' -> emits "~"
          '\x202F' -> emits "\\,"
-         '\x2026' -> emits "\\ldots{}"
+         '\x2026' -> emitcseq "\\ldots"
          '\x2018' | ligatures -> emits "`"
          '\x2019' | ligatures -> emits "'"
          '\x201C' | ligatures -> emits "``"
@@ -379,22 +370,22 @@
          '\x2013' | ligatures -> emits "--"
          _ | writerPreferAscii opts
              -> case x of
-                  'ı' -> emits "\\i "
-                  'ȷ' -> emits "\\j "
-                  'å' -> emits "\\aa "
-                  'Å' -> emits "\\AA "
-                  'ß' -> emits "\\ss "
-                  'ø' -> emits "\\o "
-                  'Ø' -> emits "\\O "
-                  'Ł' -> emits "\\L "
-                  'ł' -> emits "\\l "
-                  'æ' -> emits "\\ae "
-                  'Æ' -> emits "\\AE "
-                  'œ' -> emits "\\oe "
-                  'Œ' -> emits "\\OE "
-                  '£' -> emits "\\pounds "
-                  '€' -> emits "\\euro "
-                  '©' -> emits "\\copyright "
+                  'ı' -> emitcseq "\\i"
+                  'ȷ' -> emitcseq "\\j"
+                  'å' -> emitcseq "\\aa"
+                  'Å' -> emitcseq "\\AA"
+                  'ß' -> emitcseq "\\ss"
+                  'ø' -> emitcseq "\\o"
+                  'Ø' -> emitcseq "\\O"
+                  'Ł' -> emitcseq "\\L"
+                  'ł' -> emitcseq "\\l"
+                  'æ' -> emitcseq "\\ae"
+                  'Æ' -> emitcseq "\\AE"
+                  'œ' -> emitcseq "\\oe"
+                  'Œ' -> emitcseq "\\OE"
+                  '£' -> emitcseq "\\pounds"
+                  '€' -> emitcseq "\\euro"
+                  '©' -> emitcseq "\\copyright"
                   _   -> emitc x
            | otherwise -> emitc x
 
@@ -457,7 +448,14 @@
                     : tit ++ [RawInline "latex" "}"] )
              : bs ++ [RawBlock "latex" "\\end{block}"]
   | lvl <  slideLevel = do
-      bs <- concat `fmap` mapM (elementToBeamer slideLevel) elts
+      let isSec Sec{} = True
+          isSec _     = False
+      let (contentElts, secElts) = break isSec elts
+      let elts' = if null contentElts
+                     then secElts
+                     else Sec slideLevel [] nullAttr tit contentElts :
+                          secElts
+      bs <- concat `fmap` mapM (elementToBeamer slideLevel) elts'
       return $ Header lvl (ident,classes,kvs) tit : bs
   | otherwise = do -- lvl == slideLevel
       -- note: [fragile] is required or verbatim breaks
diff --git a/src/Text/Pandoc/Writers/Man.hs b/src/Text/Pandoc/Writers/Man.hs
--- a/src/Text/Pandoc/Writers/Man.hs
+++ b/src/Text/Pandoc/Writers/Man.hs
@@ -1,26 +1,8 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2007-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.Writers.Man
-   Copyright   : Copyright (C) 2007-2018 John MacFarlane
+   Copyright   : Copyright (C) 2007-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
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
@@ -3,27 +3,9 @@
 {-# LANGUAGE OverloadedStrings   #-}
 {-# LANGUAGE ScopedTypeVariables #-}
 {-# LANGUAGE TupleSections       #-}
-{-
-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.Writers.Markdown
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
@@ -407,7 +389,13 @@
               isEnabled Ext_markdown_in_html_blocks opts) ->
                 tagWithAttrs "div" attrs <> blankline <>
                 contents <> blankline <> "</div>" <> blankline
+           | isEnabled Ext_raw_html opts &&
+             isEnabled Ext_markdown_attribute opts ->
+                tagWithAttrs "div" attrs' <> blankline <>
+                contents <> blankline <> "</div>" <> blankline
            | otherwise -> contents <> blankline
+       where (id',classes',kvs') = attrs
+             attrs' = (id',classes',("markdown","1"):kvs')
 blockToMarkdown' opts (Plain inlines) = do
   contents <- inlineListToMarkdown opts inlines
   -- escape if para starts with ordered list marker
diff --git a/src/Text/Pandoc/Writers/MediaWiki.hs b/src/Text/Pandoc/Writers/MediaWiki.hs
--- a/src/Text/Pandoc/Writers/MediaWiki.hs
+++ b/src/Text/Pandoc/Writers/MediaWiki.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2008-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.Writers.MediaWiki
-   Copyright   : Copyright (C) 2008-2018 John MacFarlane
+   Copyright   : Copyright (C) 2008-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
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
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2007-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.Writers.Ms
-   Copyright   : Copyright (C) 2007-2018 John MacFarlane
+   Copyright   : Copyright (C) 2007-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
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
@@ -1,26 +1,8 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2017-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.Writers.Muse
-   Copyright   : Copyright (C) 2017-2018 Alexander Krotov
+   Copyright   : Copyright (C) 2017-2019 Alexander Krotov
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Alexander Krotov <ilabdsf@gmail.com>
@@ -377,11 +359,11 @@
     startsWithDot _         = False
 startsWithMarker _ [] = False
 
--- | Escape special characters for Muse if needed.
-containsFootnotes :: String -> Bool
-containsFootnotes = p
-  where p ('[':xs) = q xs || p xs
-        p (_:xs)   = p xs
+containsNotes :: Char -> Char -> String -> Bool
+containsNotes left right = p
+  where p (left':xs)
+          | left' == left = q xs || p xs
+          | otherwise = p xs
         p ""       = False
         q (x:xs)
           | x `elem` ("123456789"::String) = r xs || p xs
@@ -389,8 +371,9 @@
         q [] = False
         r ('0':xs) = r xs || p xs
         r xs       = s xs || q xs || p xs
-        s (']':_) = True
-        s (_:xs)  = p xs
+        s (right':xs)
+          | right' == right = True
+          | otherwise = p xs
         s []      = False
 
 -- | Return True if string should be escaped with <verbatim> tags
@@ -405,8 +388,10 @@
            "~~" `isInfixOf` s ||
            "[[" `isInfixOf` s ||
            ("]" `isInfixOf` s && insideLink) ||
-           containsFootnotes s
+           containsNotes '[' ']' s ||
+           containsNotes '{' '}' s
 
+-- | Escape special characters for Muse if needed.
 conditionalEscapeString :: PandocMonad m
                         => String
                         -> Muse m String
@@ -501,9 +486,9 @@
 fixOrEscape :: Bool -> Inline -> Bool
 fixOrEscape sp (Str "-") = sp
 fixOrEscape sp (Str s@('-':x:_)) = (sp && isSpace x) || isHorizontalRule s
-fixOrEscape sp (Str (";")) = not sp
+fixOrEscape sp (Str ";") = not sp
 fixOrEscape sp (Str (';':x:_)) = not sp && isSpace x
-fixOrEscape _ (Str (">")) = True
+fixOrEscape _ (Str ">") = True
 fixOrEscape _ (Str ('>':x:_)) = isSpace x
 fixOrEscape sp (Str s) = (sp && (startsWithMarker isDigit s ||
                                 startsWithMarker isAsciiLower s ||
diff --git a/src/Text/Pandoc/Writers/Native.hs b/src/Text/Pandoc/Writers/Native.hs
--- a/src/Text/Pandoc/Writers/Native.hs
+++ b/src/Text/Pandoc/Writers/Native.hs
@@ -1,26 +1,8 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
-{-
-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.Writers.Native
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Writers/ODT.hs b/src/Text/Pandoc/Writers/ODT.hs
--- a/src/Text/Pandoc/Writers/ODT.hs
+++ b/src/Text/Pandoc/Writers/ODT.hs
@@ -1,26 +1,8 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE ScopedTypeVariables #-}
-{-
-Copyright (C) 2008-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.Writers.ODT
-   Copyright   : Copyright (C) 2008-2018 John MacFarlane
+   Copyright   : Copyright (C) 2008-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Writers/OOXML.hs b/src/Text/Pandoc/Writers/OOXML.hs
--- a/src/Text/Pandoc/Writers/OOXML.hs
+++ b/src/Text/Pandoc/Writers/OOXML.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2012-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.Writers.OOXML
-   Copyright   : Copyright (C) 2012-2018 John MacFarlane
+   Copyright   : Copyright (C) 2012-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Writers/OPML.hs b/src/Text/Pandoc/Writers/OPML.hs
--- a/src/Text/Pandoc/Writers/OPML.hs
+++ b/src/Text/Pandoc/Writers/OPML.hs
@@ -1,26 +1,8 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE CPP #-}
-{-
-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.Writers.OPML
-   Copyright   : Copyright (C) 2013-2018 John MacFarlane
+   Copyright   : Copyright (C) 2013-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Writers/OpenDocument.hs b/src/Text/Pandoc/Writers/OpenDocument.hs
--- a/src/Text/Pandoc/Writers/OpenDocument.hs
+++ b/src/Text/Pandoc/Writers/OpenDocument.hs
@@ -2,28 +2,9 @@
 {-# LANGUAGE FlexibleContexts  #-}
 {-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE PatternGuards     #-}
-{-
-Copyright (C) 2008-2018 Andrea Rossato <andrea.rossato@ing.unitn.it>
-                        and John MacFarlane.
-
-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.Writers.OpenDocument
-   Copyright   : Copyright (C) 2008-2018 Andrea Rossato and John MacFarlane
+   Copyright   : Copyright (C) 2008-2019 Andrea Rossato and John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Andrea Rossato <andrea.rossato@ing.unitn.it>
diff --git a/src/Text/Pandoc/Writers/Org.hs b/src/Text/Pandoc/Writers/Org.hs
--- a/src/Text/Pandoc/Writers/Org.hs
+++ b/src/Text/Pandoc/Writers/Org.hs
@@ -1,30 +1,10 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2010-2015 Puneeth Chaganti <punchagan@gmail.com>
-              2010-2018 John MacFarlane <jgm@berkeley.edu>
-              2016-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
-
-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.Writers.Org
   Copyright    : © 2010-2015 Puneeth Chaganti <punchagan@gmail.com>
-                   2010-2018 John MacFarlane <jgm@berkeley.edu>
-                   2016-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
+                   2010-2019 John MacFarlane <jgm@berkeley.edu>
+                   2016-2019 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
diff --git a/src/Text/Pandoc/Writers/Powerpoint.hs b/src/Text/Pandoc/Writers/Powerpoint.hs
--- a/src/Text/Pandoc/Writers/Powerpoint.hs
+++ b/src/Text/Pandoc/Writers/Powerpoint.hs
@@ -1,27 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-
-
-{-
-Copyright (C) 2017-2018 Jesse Rosenthal <jrosenthal@jhu.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.Writers.Powerpoint
-   Copyright   : Copyright (C) 2017-2018 Jesse Rosenthal
+   Copyright   : Copyright (C) 2017-2019 Jesse Rosenthal
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
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
@@ -1,27 +1,8 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE PatternGuards #-}
-
-{-
-Copyright (C) 2017-2018 Jesse Rosenthal <jrosenthal@jhu.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.Writers.Powerpoint.Output
-   Copyright   : Copyright (C) 2017-2018 Jesse Rosenthal
+   Copyright   : Copyright (C) 2017-2019 Jesse Rosenthal
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
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,28 +1,9 @@
 {-# LANGUAGE NoImplicitPrelude          #-}
 {-# LANGUAGE PatternGuards              #-}
 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
-
-{-
-Copyright (C) 2017-2018 Jesse Rosenthal <jrosenthal@jhu.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.Writers.Powerpoint.Presentation
-   Copyright   : Copyright (C) 2017-2018 Jesse Rosenthal
+   Copyright   : Copyright (C) 2017-2019 Jesse Rosenthal
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
@@ -382,6 +363,9 @@
     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 (_, ["underline"], _) ils) =
+  local (\r -> r{envRunProps = (envRunProps r){rPropUnderline=True}}) $
+  inlinesToParElems ils
 inlineToParElems (Span _ ils) = inlinesToParElems ils
 inlineToParElems (Quoted quoteType ils) =
   inlinesToParElems $ [Str open] ++ ils ++ [Str close]
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
@@ -1,26 +1,8 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
-{-
-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.Writers.RST
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Writers/RTF.hs b/src/Text/Pandoc/Writers/RTF.hs
--- a/src/Text/Pandoc/Writers/RTF.hs
+++ b/src/Text/Pandoc/Writers/RTF.hs
@@ -1,26 +1,8 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE ScopedTypeVariables #-}
-{-
-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.Writers.RTF
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Writers/Roff.hs b/src/Text/Pandoc/Writers/Roff.hs
--- a/src/Text/Pandoc/Writers/Roff.hs
+++ b/src/Text/Pandoc/Writers/Roff.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2007-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.Writers.Roff
-   Copyright   : Copyright (C) 2007-2018 John MacFarlane
+   Copyright   : Copyright (C) 2007-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Writers/Shared.hs b/src/Text/Pandoc/Writers/Shared.hs
--- a/src/Text/Pandoc/Writers/Shared.hs
+++ b/src/Text/Pandoc/Writers/Shared.hs
@@ -1,26 +1,8 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
-{-
-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.Writers.Shared
-   Copyright   : Copyright (C) 2013-2018 John MacFarlane
+   Copyright   : Copyright (C) 2013-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Writers/TEI.hs b/src/Text/Pandoc/Writers/TEI.hs
--- a/src/Text/Pandoc/Writers/TEI.hs
+++ b/src/Text/Pandoc/Writers/TEI.hs
@@ -1,27 +1,9 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE PatternGuards     #-}
-{-
-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.Writers.Docbook
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Writers/Texinfo.hs b/src/Text/Pandoc/Writers/Texinfo.hs
--- a/src/Text/Pandoc/Writers/Texinfo.hs
+++ b/src/Text/Pandoc/Writers/Texinfo.hs
@@ -1,27 +1,8 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
-{-
-Copyright (C) 2008-2018 John MacFarlane
-              2012 Peter Wang
-
-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.Writers.Texinfo
-   Copyright   : Copyright (C) 2008-2018 John MacFarlane
+   Copyright   : Copyright (C) 2008-2019 John MacFarlane
                                2012 Peter Wang
    License     : GNU GPL, version 2 or above
 
diff --git a/src/Text/Pandoc/Writers/Textile.hs b/src/Text/Pandoc/Writers/Textile.hs
--- a/src/Text/Pandoc/Writers/Textile.hs
+++ b/src/Text/Pandoc/Writers/Textile.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2010-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.Writers.Textile
-   Copyright   : Copyright (C) 2010-2018 John MacFarlane
+   Copyright   : Copyright (C) 2010-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/src/Text/Pandoc/Writers/ZimWiki.hs b/src/Text/Pandoc/Writers/ZimWiki.hs
--- a/src/Text/Pandoc/Writers/ZimWiki.hs
+++ b/src/Text/Pandoc/Writers/ZimWiki.hs
@@ -1,26 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-Copyright (C) 2008-2018 John MacFarlane <jgm@berkeley.edu>
-              2017-2018 Alex Ivkin
-
-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.Writers.ZimWiki
-   Copyright   : Copyright (C) 2008-2018 John MacFarlane, 2017-2018 Alex Ivkin
+   Copyright   : Copyright (C) 2008-2019 John MacFarlane, 2017-2019 Alex Ivkin
    License     : GNU GPL, version 2 or above
 
    Maintainer  : Alex Ivkin <alex@ivkin.net>
diff --git a/src/Text/Pandoc/XML.hs b/src/Text/Pandoc/XML.hs
--- a/src/Text/Pandoc/XML.hs
+++ b/src/Text/Pandoc/XML.hs
@@ -1,25 +1,7 @@
 {-# LANGUAGE NoImplicitPrelude #-}
-{-
-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.XML
-   Copyright   : Copyright (C) 2006-2018 John MacFarlane
+   Copyright   : Copyright (C) 2006-2019 John MacFarlane
    License     : GNU GPL, version 2 or above
 
    Maintainer  : John MacFarlane <jgm@berkeley.edu>
diff --git a/stack.yaml b/stack.yaml
--- a/stack.yaml
+++ b/stack.yaml
@@ -10,18 +10,12 @@
     debug: false
 packages:
 - '.'
-# See https://github.com/haskell-foundation/foundation/pull/503
-# We can go back to released foundation when this is fixed.
-- location:
-    git: https://github.com/jgm/foundation
-    commit: '4294e39'
-  subdirs:
-  - foundation
-  extra-dep: true
 extra-deps:
-- pandoc-citeproc-0.16
+- pandoc-citeproc-0.16.1.1
+- skylighting-0.7.7
+- skylighting-core-0.7.7
 - ipynb-0.1
-- texmath-0.11.2
+- texmath-0.11.2.1
 ghc-options:
    "$locals": -fhide-source-paths -XNoImplicitPrelude
-resolver: lts-13.5
+resolver: lts-13.9
diff --git a/test/Tests/Command.hs b/test/Tests/Command.hs
--- a/test/Tests/Command.hs
+++ b/test/Tests/Command.hs
@@ -1,4 +1,15 @@
 {-# LANGUAGE NoImplicitPrelude #-}
+{- |
+   Module      : Tests.Command
+   Copyright   : © 2006-2019 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley@edu>
+   Stability   : alpha
+   Portability : portable
+
+Run commands, and test results, defined in markdown files.
+-}
 module Tests.Command (findPandoc, runTest, tests)
 where
 
@@ -53,13 +64,12 @@
                   return $ TestError ec
   assertBool (show result) (result == TestPassed)
 
-tests :: TestTree
+tests :: FilePath -> TestTree
 {-# NOINLINE tests #-}
-tests = unsafePerformIO $ do
-  pandocpath <- findPandoc
+tests pandocPath = unsafePerformIO $ do
   files <- filter (".md" `isSuffixOf`) <$>
                getDirectoryContents "command"
-  let cmds = map (extractCommandTest pandocpath) files
+  let cmds = map (extractCommandTest pandocPath) files
   return $ testGroup "Command:" cmds
 
 isCodeBlock :: Block -> Bool
diff --git a/test/Tests/Helpers.hs b/test/Tests/Helpers.hs
--- a/test/Tests/Helpers.hs
+++ b/test/Tests/Helpers.hs
@@ -2,8 +2,17 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE FlexibleInstances    #-}
 {-# LANGUAGE TypeSynonymInstances #-}
--- Utility functions for the test suite.
+{- |
+   Module      : Tests.Helpers
+   Copyright   : © 2006-2019 John MacFarlane
+   License     : GNU GPL, version 2 or above
 
+   Maintainer  : John MacFarlane <jgm@berkeley@edu>
+   Stability   : alpha
+   Portability : portable
+
+Utility functions for the test suite.
+-}
 module Tests.Helpers ( test
                      , TestResult(..)
                      , showDiff
diff --git a/test/Tests/Lua.hs b/test/Tests/Lua.hs
--- a/test/Tests/Lua.hs
+++ b/test/Tests/Lua.hs
@@ -1,5 +1,16 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Lua
+   Copyright   : © 2017-2019 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert@zeitkraut.de>
+   Stability   : alpha
+   Portability : portable
+
+Unit and integration tests for pandoc's Lua subsystem.
+-}
 module Tests.Lua ( tests ) where
 
 import Prelude
diff --git a/test/Tests/Old.hs b/test/Tests/Old.hs
--- a/test/Tests/Old.hs
+++ b/test/Tests/Old.hs
@@ -1,4 +1,15 @@
 {-# LANGUAGE NoImplicitPrelude #-}
+{- |
+   Module      : Tests.Old
+   Copyright   : © 2006-2019 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley@edu>
+   Stability   : alpha
+   Portability : portable
+
+"Old" style tests (comparing output to golden files).
+-}
 module Tests.Old (tests) where
 
 import Prelude
@@ -6,221 +17,238 @@
 import Prelude hiding (readFile)
 import System.Exit
 import System.FilePath (joinPath, splitDirectories, (<.>), (</>))
-import System.IO.Temp (withTempFile)
-import System.Process (runProcess, waitForProcess)
+import Text.Pandoc.Process (pipeProcess)
 import Test.Tasty (TestTree, testGroup)
 import Test.Tasty.Golden.Advanced (goldenTest)
 import Tests.Helpers hiding (test)
 import qualified Text.Pandoc.UTF8 as UTF8
 
-tests :: [TestTree]
-tests = [ testGroup "markdown"
-          [ testGroup "writer"
-            $ writerTests "markdown" ++ lhsWriterTests "markdown"
-          , testGroup "reader"
-            [ test "basic" ["-r", "markdown", "-w", "native", "-s"]
-              "testsuite.txt" "testsuite.native"
-            , test "tables" ["-r", "markdown", "-w", "native", "--columns=80"]
-              "tables.txt" "tables.native"
-            , test "pipe tables" ["-r", "markdown", "-w", "native", "--columns=80"]
-              "pipe-tables.txt" "pipe-tables.native"
-            , test "more" ["-r", "markdown", "-w", "native", "-s"]
-              "markdown-reader-more.txt" "markdown-reader-more.native"
-            , lhsReaderTest "markdown+lhs"
-            ]
-          , testGroup "citations"
-            [ test "citations" ["-r", "markdown", "-w", "native"]
-              "markdown-citations.txt" "markdown-citations.native"
-            ]
-          ]
-        , testGroup "rst"
-          [ testGroup "writer" (writerTests "rst" ++ lhsWriterTests "rst")
-          , testGroup "reader"
-            [ test "basic" ["-r", "rst+smart", "-w", "native",
-              "-s", "--columns=80"] "rst-reader.rst" "rst-reader.native"
-            , test "tables" ["-r", "rst", "-w", "native", "--columns=80"]
-              "tables.rst" "tables-rstsubset.native"
-            , lhsReaderTest "rst+lhs"
-            ]
-          ]
-        , testGroup "latex"
-          [ testGroup "writer" (writerTests "latex" ++ lhsWriterTests "latex")
-          , testGroup "reader"
-            [ test "basic" ["-r", "latex+raw_tex", "-w", "native", "-s"]
-              "latex-reader.latex" "latex-reader.native"
-            , lhsReaderTest "latex+lhs"
-            ]
-          ]
-        , testGroup "html"
-          [ testGroup "writer" (writerTests "html4" ++ writerTests "html5" ++
-                                lhsWriterTests "html")
-          , test "reader" ["-r", "html", "-w", "native", "-s"]
-            "html-reader.html" "html-reader.native"
-          ]
-        , testGroup "s5"
-          [ s5WriterTest "basic" ["-s"] "s5"
-          , s5WriterTest "fancy" ["-s","--mathjax","-i"] "s5"
-          , s5WriterTest "fragment" [] "html4"
-          , s5WriterTest "inserts"  ["-s", "-H", "insert",
-            "-B", "insert", "-A", "insert", "-c", "main.css"] "html4"
-          ]
-        , testGroup "textile"
-          [ testGroup "writer" $ writerTests "textile"
-          , test "reader" ["-r", "textile", "-w", "native", "-s"]
-            "textile-reader.textile" "textile-reader.native"
-          ]
-        , testGroup "docbook"
-          [ testGroup "writer" $ writerTests "docbook4"
-          , test "reader" ["-r", "docbook", "-w", "native", "-s"]
-            "docbook-reader.docbook" "docbook-reader.native"
-          , test "reader" ["-r", "docbook", "-w", "native", "-s"]
-            "docbook-xref.docbook" "docbook-xref.native"
-          ]
-        , testGroup "docbook5"
-          [ testGroup "writer" $ writerTests "docbook5"
-          ]
-        , testGroup "jats"
-          [ testGroup "writer" $ writerTests "jats"
-          , test "reader" ["-r", "jats", "-w", "native", "-s"]
-            "jats-reader.xml" "jats-reader.native"
-          ]
-        , testGroup "native"
-          [ testGroup "writer" $ writerTests "native"
-          , test "reader" ["-r", "native", "-w", "native", "-s"]
-            "testsuite.native" "testsuite.native"
-          ]
-        , testGroup "fb2"
-          [ fb2WriterTest "basic" [] "fb2/basic.markdown" "fb2/basic.fb2"
-          , fb2WriterTest "titles" [] "fb2/titles.markdown" "fb2/titles.fb2"
-          , 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"
-          ]
-        , testGroup "mediawiki"
-          [ testGroup "writer" $ writerTests "mediawiki"
-          , test "reader" ["-r", "mediawiki", "-w", "native", "-s"]
-            "mediawiki-reader.wiki" "mediawiki-reader.native"
-          ]
-        , testGroup "vimwiki"
-          [ test "reader" ["-r", "vimwiki", "-w", "native", "-s"]
-            "vimwiki-reader.wiki" "vimwiki-reader.native"
-          ]
-        , testGroup "dokuwiki"
-          [ testGroup "writer" $ writerTests "dokuwiki"
-          , test "inline_formatting" ["-r", "native", "-w", "dokuwiki", "-s"]
-            "dokuwiki_inline_formatting.native" "dokuwiki_inline_formatting.dokuwiki"
-          , test "multiblock table" ["-r", "native", "-w", "dokuwiki", "-s"]
-            "dokuwiki_multiblock_table.native" "dokuwiki_multiblock_table.dokuwiki"
-          , test "external images" ["-r", "native", "-w", "dokuwiki", "-s"]
-            "dokuwiki_external_images.native" "dokuwiki_external_images.dokuwiki"
-          ]
-        , testGroup "opml"
-          [ test "basic" ["-r", "native", "-w", "opml", "--columns=78", "-s"]
-             "testsuite.native" "writer.opml"
-          , test "reader" ["-r", "opml", "-w", "native", "-s"]
-            "opml-reader.opml" "opml-reader.native"
-          ]
-        , testGroup "haddock"
-          [ testGroup "writer" $ writerTests "haddock"
-          , test "reader" ["-r", "haddock", "-w", "native", "-s"]
-            "haddock-reader.haddock" "haddock-reader.native"
-          ]
-        , testGroup "txt2tags"
-          [ test "reader" ["-r", "t2t", "-w", "native", "-s"]
-              "txt2tags.t2t" "txt2tags.native" ]
-        , testGroup "epub" [
-            test "features" ["-r", "epub", "-w", "native"]
-              "epub/features.epub" "epub/features.native"
-          , test "wasteland" ["-r", "epub", "-w", "native"]
-              "epub/wasteland.epub" "epub/wasteland.native"
-          , test "formatting" ["-r", "epub", "-w", "native"]
-              "epub/formatting.epub" "epub/formatting.native"
-          ]
-        , testGroup "twiki"
-          [ test "reader" ["-r", "twiki", "-w", "native", "-s"]
-              "twiki-reader.twiki" "twiki-reader.native" ]
-        , testGroup "tikiwiki"
-          [ test "reader" ["-r", "tikiwiki", "-w", "native", "-s"]
-              "tikiwiki-reader.tikiwiki" "tikiwiki-reader.native" ]
-        , testGroup "other writers" $ map (\f -> testGroup f $ writerTests f)
-          [ "opendocument" , "context" , "texinfo", "icml", "tei"
-          , "man" , "plain" , "rtf", "org", "asciidoc", "zimwiki"
-          ]
-        , testGroup "writers-lang-and-dir"
-          [ test "latex" ["-f", "native", "-t", "latex", "-s"]
-            "writers-lang-and-dir.native" "writers-lang-and-dir.latex"
-          , test "context" ["-f", "native", "-t", "context", "-s"]
-            "writers-lang-and-dir.native" "writers-lang-and-dir.context"
-          ]
-        , testGroup "muse"
-          [ testGroup "writer" $ writerTests "muse"
-          ]
-        , testGroup "ms"
-          [ testGroup "writer" $ writerTests "ms"
-          ]
-        , testGroup "creole"
-          [ test "reader" ["-r", "creole", "-w", "native", "-s"]
-            "creole-reader.txt" "creole-reader.native"
-          ]
-        , testGroup "custom writer"
-          [ test "basic" ["-f", "native", "-t", "../data/sample.lua"]
-            "testsuite.native" "writer.custom"
-          , test "tables" ["-f", "native", "-t", "../data/sample.lua"]
-            "tables.native" "tables.custom"
-          ]
-        , testGroup "man"
-          [ test "reader" ["-r", "man", "-w", "native", "-s"]
-            "man-reader.man" "man-reader.native"
-          ]
-        , testGroup "org"
-          [ test "reader" ["-r", "org", "-w", "native", "-s"]
-            "org-select-tags.org" "org-select-tags.native"
-          ]
-        ]
+tests :: FilePath -> [TestTree]
+tests pandocPath =
+  [ testGroup "markdown"
+    [ testGroup "writer"
+      $ writerTests' "markdown" ++ lhsWriterTests' "markdown"
+    , testGroup "reader"
+      [ test' "basic" ["-r", "markdown", "-w", "native", "-s"]
+        "testsuite.txt" "testsuite.native"
+      , test' "tables" ["-r", "markdown", "-w", "native", "--columns=80"]
+        "tables.txt" "tables.native"
+      , test' "pipe tables" ["-r", "markdown", "-w", "native", "--columns=80"]
+        "pipe-tables.txt" "pipe-tables.native"
+      , test' "more" ["-r", "markdown", "-w", "native", "-s"]
+        "markdown-reader-more.txt" "markdown-reader-more.native"
+      , lhsReaderTest' "markdown+lhs"
+      ]
+    , testGroup "citations"
+      [ test' "citations" ["-r", "markdown", "-w", "native"]
+        "markdown-citations.txt" "markdown-citations.native"
+      ]
+    ]
+  , testGroup "rst"
+    [ testGroup "writer" (writerTests' "rst" ++ lhsWriterTests' "rst")
+    , testGroup "reader"
+      [ test' "basic" ["-r", "rst+smart", "-w", "native",
+        "-s", "--columns=80"] "rst-reader.rst" "rst-reader.native"
+      , test' "tables" ["-r", "rst", "-w", "native", "--columns=80"]
+        "tables.rst" "tables-rstsubset.native"
+      , lhsReaderTest' "rst+lhs"
+      ]
+    ]
+  , testGroup "latex"
+    [ testGroup "writer"
+        (writerTests' "latex" ++ lhsWriterTests' "latex")
+    , testGroup "reader"
+      [ test' "basic" ["-r", "latex+raw_tex", "-w", "native", "-s"]
+        "latex-reader.latex" "latex-reader.native"
+      , lhsReaderTest' "latex+lhs"
+      ]
+    ]
+  , testGroup "html"
+    [ testGroup "writer" (writerTests' "html4" ++ writerTests' "html5" ++
+        lhsWriterTests' "html")
+    , test' "reader" ["-r", "html", "-w", "native", "-s"]
+      "html-reader.html" "html-reader.native"
+    ]
+  , testGroup "s5"
+    [ s5WriterTest' "basic" ["-s"] "s5"
+    , s5WriterTest' "fancy" ["-s","--mathjax","-i"] "s5"
+    , s5WriterTest' "fragment" [] "html4"
+    , s5WriterTest' "inserts"  ["-s", "-H", "insert",
+      "-B", "insert", "-A", "insert", "-c", "main.css"] "html4"
+    ]
+  , testGroup "textile"
+    [ testGroup "writer" $ writerTests' "textile"
+    , test' "reader" ["-r", "textile", "-w", "native", "-s"]
+      "textile-reader.textile" "textile-reader.native"
+    ]
+  , testGroup "docbook"
+    [ testGroup "writer" $ writerTests' "docbook4"
+    , test' "reader" ["-r", "docbook", "-w", "native", "-s"]
+      "docbook-reader.docbook" "docbook-reader.native"
+    , test' "reader" ["-r", "docbook", "-w", "native", "-s"]
+      "docbook-xref.docbook" "docbook-xref.native"
+    ]
+  , testGroup "docbook5"
+    [ testGroup "writer" $ writerTests' "docbook5"
+    ]
+  , testGroup "jats"
+    [ testGroup "writer" $ writerTests' "jats"
+    , test' "reader" ["-r", "jats", "-w", "native", "-s"]
+      "jats-reader.xml" "jats-reader.native"
+    ]
+  , testGroup "native"
+    [ testGroup "writer" $ writerTests' "native"
+    , test' "reader" ["-r", "native", "-w", "native", "-s"]
+      "testsuite.native" "testsuite.native"
+    ]
+  , testGroup "fb2"
+    [ fb2WriterTest' "basic" [] "fb2/basic.markdown" "fb2/basic.fb2"
+    , fb2WriterTest' "titles" [] "fb2/titles.markdown" "fb2/titles.fb2"
+    , 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"
+    ]
+  , testGroup "mediawiki"
+    [ testGroup "writer" $ writerTests' "mediawiki"
+    , test' "reader" ["-r", "mediawiki", "-w", "native", "-s"]
+      "mediawiki-reader.wiki" "mediawiki-reader.native"
+    ]
+  , testGroup "vimwiki"
+    [ test' "reader" ["-r", "vimwiki", "-w", "native", "-s"]
+      "vimwiki-reader.wiki" "vimwiki-reader.native"
+    ]
+  , testGroup "dokuwiki"
+    [ testGroup "writer" $ writerTests' "dokuwiki"
+    , test' "inline_formatting" ["-r", "native", "-w", "dokuwiki", "-s"]
+      "dokuwiki_inline_formatting.native" "dokuwiki_inline_formatting.dokuwiki"
+    , test' "multiblock table" ["-r", "native", "-w", "dokuwiki", "-s"]
+      "dokuwiki_multiblock_table.native" "dokuwiki_multiblock_table.dokuwiki"
+    , test' "external images" ["-r", "native", "-w", "dokuwiki", "-s"]
+      "dokuwiki_external_images.native" "dokuwiki_external_images.dokuwiki"
+    ]
+  , testGroup "opml"
+    [ test' "basic" ["-r", "native", "-w", "opml", "--columns=78", "-s"]
+       "testsuite.native" "writer.opml"
+    , test' "reader" ["-r", "opml", "-w", "native", "-s"]
+      "opml-reader.opml" "opml-reader.native"
+    ]
+  , testGroup "haddock"
+    [ testGroup "writer" $ writerTests' "haddock"
+    , test' "reader" ["-r", "haddock", "-w", "native", "-s"]
+      "haddock-reader.haddock" "haddock-reader.native"
+    ]
+  , testGroup "txt2tags"
+    [ test' "reader" ["-r", "t2t", "-w", "native", "-s"]
+        "txt2tags.t2t" "txt2tags.native" ]
+  , testGroup "epub" [
+      test' "features" ["-r", "epub", "-w", "native"]
+        "epub/features.epub" "epub/features.native"
+    , test' "wasteland" ["-r", "epub", "-w", "native"]
+        "epub/wasteland.epub" "epub/wasteland.native"
+    , test' "formatting" ["-r", "epub", "-w", "native"]
+        "epub/formatting.epub" "epub/formatting.native"
+    ]
+  , testGroup "twiki"
+    [ test' "reader" ["-r", "twiki", "-w", "native", "-s"]
+        "twiki-reader.twiki" "twiki-reader.native" ]
+  , testGroup "tikiwiki"
+    [ test' "reader" ["-r", "tikiwiki", "-w", "native", "-s"]
+        "tikiwiki-reader.tikiwiki" "tikiwiki-reader.native" ]
+  , testGroup "other writers" $ map (\f -> testGroup f $ writerTests' f)
+    [ "opendocument" , "context" , "texinfo", "icml", "tei"
+    , "man" , "plain" , "rtf", "org", "asciidoc", "asciidoctor", "zimwiki"
+    ]
+  , testGroup "writers-lang-and-dir"
+    [ test' "latex" ["-f", "native", "-t", "latex", "-s"]
+      "writers-lang-and-dir.native" "writers-lang-and-dir.latex"
+    , test' "context" ["-f", "native", "-t", "context", "-s"]
+      "writers-lang-and-dir.native" "writers-lang-and-dir.context"
+    ]
+  , testGroup "muse"
+    [ testGroup "writer" $ writerTests' "muse"
+    ]
+  , testGroup "ms"
+    [ testGroup "writer" $ writerTests' "ms"
+    ]
+  , testGroup "creole"
+    [ test' "reader" ["-r", "creole", "-w", "native", "-s"]
+      "creole-reader.txt" "creole-reader.native"
+    ]
+  , testGroup "custom writer"
+    [ test' "basic" ["-f", "native", "-t", "../data/sample.lua"]
+      "testsuite.native" "writer.custom"
+    , test' "tables" ["-f", "native", "-t", "../data/sample.lua"]
+      "tables.native" "tables.custom"
+    ]
+  , testGroup "man"
+    [ test' "reader" ["-r", "man", "-w", "native", "-s"]
+      "man-reader.man" "man-reader.native"
+    ]
+  , testGroup "org"
+    [ test' "reader" ["-r", "org", "-w", "native", "-s"]
+      "org-select-tags.org" "org-select-tags.native"
+    ]
+  , testGroup "ipynb"
+    [ test' "reader" ["-f", "ipynb", "-t", "native", "-s"]
+      "ipynb/simple.ipynb" "ipynb/simple.out.native"
+    , test' "writer" ["-f", "native", "-t", "ipynb", "-s"]
+      "ipynb/simple.in.native" "ipynb/simple.ipynb"
+    ]
+  ]
+ where
+    test'           = test pandocPath
+    writerTests'    = writerTests pandocPath
+    s5WriterTest'   = s5WriterTest pandocPath
+    fb2WriterTest'  = fb2WriterTest pandocPath
+    lhsWriterTests' = lhsWriterTests pandocPath
+    lhsReaderTest'  = lhsReaderTest pandocPath
 
 -- makes sure file is fully closed after reading
 readFile' :: FilePath -> IO String
 readFile' f = do s <- UTF8.readFile f
                  return $! (length s `seq` s)
 
-lhsWriterTests :: String -> [TestTree]
-lhsWriterTests format
+lhsWriterTests :: FilePath -> String -> [TestTree]
+lhsWriterTests pandocPath format
   = [ t "lhs to normal" format
     , t "lhs to lhs"    (format ++ "+lhs")
     ]
   where
-    t n f = test n ["--wrap=preserve", "-r", "native", "-s", "-w", f]
+    t n f = test pandocPath
+             n ["--wrap=preserve", "-r", "native", "-s", "-w", f]
              "lhs-test.native" ("lhs-test" <.> f)
 
-lhsReaderTest :: String -> TestTree
-lhsReaderTest format =
-  test "lhs" ["-r", format, "-w", "native"]
+lhsReaderTest :: FilePath -> String -> TestTree
+lhsReaderTest pandocPath format =
+  test pandocPath "lhs" ["-r", format, "-w", "native"]
     ("lhs-test" <.> format) norm
    where norm = if format == "markdown+lhs"
                    then "lhs-test-markdown.native"
                    else "lhs-test.native"
 
-writerTests :: String -> [TestTree]
-writerTests format
-  = [ test "basic"  (opts ++ ["-s"]) "testsuite.native" ("writer" <.> format)
-    , test "tables" opts             "tables.native"    ("tables" <.> format)
+writerTests :: FilePath -> String -> [TestTree]
+writerTests pandocPath format
+  = [ test pandocPath
+        "basic"  (opts ++ ["-s"]) "testsuite.native" ("writer" <.> format)
+    , test pandocPath
+       "tables" opts             "tables.native"    ("tables" <.> format)
     ]
   where
     opts = ["-r", "native", "-w", format, "--columns=78",
             "--variable", "pandoc-version="]
 
-s5WriterTest :: String -> [String] -> String -> TestTree
-s5WriterTest modifier opts format
-  = test (format ++ " writer (" ++ modifier ++ ")")
+s5WriterTest :: FilePath -> String -> [String] -> String -> TestTree
+s5WriterTest pandocPath modifier opts format
+  = test pandocPath (format ++ " writer (" ++ modifier ++ ")")
     (["-r", "native", "-w", format] ++ opts)
     "s5.native"  ("s5-" ++ modifier <.> "html")
 
-fb2WriterTest :: String -> [String] -> String -> String -> TestTree
-fb2WriterTest title opts inputfile normfile =
-  testWithNormalize (ignoreBinary . formatXML)
+fb2WriterTest :: FilePath -> String -> [String] -> String -> String -> TestTree
+fb2WriterTest pandocPath title opts inputfile normfile =
+  testWithNormalize (ignoreBinary . formatXML) pandocPath
                     title (["-t", "fb2"]++opts) inputfile normfile
   where
     formatXML xml = splitTags $ zip xml (drop 1 xml)
@@ -232,7 +260,8 @@
     startsWith tag str = all (uncurry (==)) $ zip tag str
 
 -- | Run a test without normalize function, return True if test passed.
-test :: String    -- ^ Title of test
+test :: FilePath  -- ^ Path of pandoc executable
+     -> String    -- ^ Title of test
      -> [String]  -- ^ Options to pass to pandoc
      -> String    -- ^ Input filepath
      -> FilePath  -- ^ Norm (for test results) filepath
@@ -241,19 +270,17 @@
 
 -- | Run a test with normalize function, return True if test passed.
 testWithNormalize  :: (String -> String) -- ^ Normalize function for output
+                   -> FilePath  -- ^ Path to pandoc executable
                    -> String    -- ^ Title of test
                    -> [String]  -- ^ Options to pass to pandoc
                    -> String    -- ^ Input filepath
                    -> FilePath  -- ^ Norm (for test results) filepath
                    -> TestTree
-testWithNormalize normalizer testname opts inp norm =
+testWithNormalize normalizer pandocPath testname opts inp norm =
   goldenTest testname getExpected getActual
     (compareValues norm options) updateGolden
   where getExpected = normalizer <$> readFile' norm
-        getActual   =
-          withTempFile "." "pandoc-test" $ \outputPath hOut -> do
-            withTempFile "." "pandoc-test" $ \errorPath hErr -> do
-              pandocPath <- findPandoc
+        getActual   = do
               let mbDynlibDir = findDynlibDir (reverse $
                                  splitDirectories pandocPath)
               let dynlibEnv = case mbDynlibDir of
@@ -263,19 +290,12 @@
               let env = dynlibEnv ++
                         [("TMP","."),("LANG","en_US.UTF-8"),("HOME", "./"),
                          ("pandoc_datadir","..")]
-              ph <- runProcess pandocPath options Nothing
-                    (Just env) Nothing (Just hOut) (Just hErr)
-              ec <- waitForProcess ph
+              (ec, out) <- pipeProcess (Just env) pandocPath options mempty
               if ec == ExitSuccess
-                 then
+                 then return $ filter (/='\r') . normalizer
+                             $ UTF8.toStringLazy out
                    -- filter \r so the tests will work on Windows machines
-                   (filter (/='\r') . normalizer) <$> readFile' outputPath
-                 else do
-                   errcontents <- UTF8.readFile errorPath
-                   fail $ "Pandoc failed with " ++ show ec ++
-                           if null errcontents
-                              then ""
-                              else '\n':errcontents
+                 else fail $ "Pandoc failed with error code " ++ show ec
         updateGolden = UTF8.writeFile norm
         options = ["--quiet"] ++ [inp] ++ opts
 
diff --git a/test/Tests/Readers/Creole.hs b/test/Tests/Readers/Creole.hs
--- a/test/Tests/Readers/Creole.hs
+++ b/test/Tests/Readers/Creole.hs
@@ -1,5 +1,17 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Creole
+   Copyright   : © 2017 Sascha Wilde
+                   2017-2019 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Sascha Wilde <wilde@sha-bang.de>
+   Stability   : alpha
+   Portability : portable
+
+Tests for the creole reader.
+-}
 module Tests.Readers.Creole (tests) where
 
 import Prelude
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
@@ -1,4 +1,15 @@
 {-# LANGUAGE NoImplicitPrelude #-}
+{- |
+   Module      : Tests.Readers.Docx
+   Copyright   : © 2017-2019 Jesse Rosenthal, John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Jesse Rosenthal <jrosenthal@jhu.edu>
+   Stability   : alpha
+   Portability : portable
+
+Tests for the word docx reader.
+-}
 module Tests.Readers.Docx (tests) where
 
 import Prelude
@@ -115,8 +126,14 @@
 testMediaBag name docxFile = unsafePerformIO $ testMediaBagIO name docxFile
 
 tests :: [TestTree]
-tests = [ testGroup "inlines"
+tests = [ testGroup "document"
           [ testCompare
+            "allow different document.xml file as defined in _rels/.rels"
+            "docx/alternate_document_path.docx"
+            "docx/alternate_document_path.native"
+          ]
+        , testGroup "inlines"
+          [ testCompare
             "font formatting"
             "docx/inline_formatting.docx"
             "docx/inline_formatting.native"
@@ -169,6 +186,10 @@
             "docx/trailing_spaces_in_formatting.docx"
             "docx/trailing_spaces_in_formatting.native"
           , testCompare
+            "remove trailing spaces from last inline"
+            "docx/trim_last_inline.docx"
+            "docx/trim_last_inline.native"
+          , testCompare
             "inline code (with VerbatimChar style)"
             "docx/inline_code.docx"
             "docx/inline_code.native"
@@ -181,6 +202,10 @@
             "docx/sdt_elements.docx"
             "docx/sdt_elements.native"
           , testCompare
+            "Structured Document Tags in footnotes"
+            "docx/sdt_in_footnote.docx"
+            "docx/sdt_in_footnote.native"
+          , testCompare
             "nested Structured Document Tags"
             "docx/nested_sdt.docx"
             "docx/nested_sdt.native"
@@ -411,5 +436,4 @@
             "docx/metadata_after_normal.docx"
             "docx/metadata_after_normal.native"
           ]
-
         ]
diff --git a/test/Tests/Readers/DokuWiki.hs b/test/Tests/Readers/DokuWiki.hs
--- a/test/Tests/Readers/DokuWiki.hs
+++ b/test/Tests/Readers/DokuWiki.hs
@@ -1,6 +1,17 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings   #-}
 {-# LANGUAGE ScopedTypeVariables #-}
+{- |
+   Module      : Tests.Readers.DokuWiki
+   Copyright   : © 2018-2019 Alexander Krotov
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Alexander Krotov
+   Stability   : alpha
+   Portability : portable
+
+Tests for DokuWiki reader.
+-}
 module Tests.Readers.DokuWiki (tests) where
 
 import Prelude
diff --git a/test/Tests/Readers/EPUB.hs b/test/Tests/Readers/EPUB.hs
--- a/test/Tests/Readers/EPUB.hs
+++ b/test/Tests/Readers/EPUB.hs
@@ -1,4 +1,15 @@
 {-# LANGUAGE NoImplicitPrelude #-}
+{- |
+   Module      : Tests.Readers.EPUB
+   Copyright   : © 2006-2019 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.eu>
+   Stability   : alpha
+   Portability : portable
+
+Tests for the EPUB mediabag.
+-}
 module Tests.Readers.EPUB (tests) where
 
 import Prelude
diff --git a/test/Tests/Readers/FB2.hs b/test/Tests/Readers/FB2.hs
--- a/test/Tests/Readers/FB2.hs
+++ b/test/Tests/Readers/FB2.hs
@@ -1,5 +1,15 @@
 {-# LANGUAGE NoImplicitPrelude #-}
+{- |
+   Module      : Tests.Readers.FB2
+   Copyright   : © 2018-2019 Alexander Krotov
+   License     : GNU GPL, version 2 or above
 
+   Maintainer  : © 2018-2019 Alexander Krotov <ilabdsf@gmail.com>
+   Stability   : alpha
+   Portability : portable
+
+Tests for the EPUB mediabag.
+-}
 module Tests.Readers.FB2 (tests) where
 
 import Prelude
diff --git a/test/Tests/Readers/HTML.hs b/test/Tests/Readers/HTML.hs
--- a/test/Tests/Readers/HTML.hs
+++ b/test/Tests/Readers/HTML.hs
@@ -1,5 +1,16 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.HTML
+   Copyright   : © 2006-2019 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Tests for the HTML reader.
+-}
 module Tests.Readers.HTML (tests) where
 
 import Prelude
diff --git a/test/Tests/Readers/JATS.hs b/test/Tests/Readers/JATS.hs
--- a/test/Tests/Readers/JATS.hs
+++ b/test/Tests/Readers/JATS.hs
@@ -1,5 +1,16 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.JATS
+   Copyright   : © 2017 Hamish Mackenzie
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Hamish Mackenzie <Hamish.K.Mackenzie@googlemail.com>
+   Stability   : alpha
+   Portability : portable
+
+Tests for the JATS reader.
+-}
 module Tests.Readers.JATS (tests) where
 
 import Prelude
diff --git a/test/Tests/Readers/LaTeX.hs b/test/Tests/Readers/LaTeX.hs
--- a/test/Tests/Readers/LaTeX.hs
+++ b/test/Tests/Readers/LaTeX.hs
@@ -1,5 +1,16 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.LaTeX
+   Copyright   : © 2006-2019 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Tests for the LaTeX reader.
+-}
 module Tests.Readers.LaTeX (tests) where
 
 import Prelude
diff --git a/test/Tests/Readers/Man.hs b/test/Tests/Readers/Man.hs
--- a/test/Tests/Readers/Man.hs
+++ b/test/Tests/Readers/Man.hs
@@ -1,4 +1,16 @@
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Man
+   Copyright   : © 2018-2019 Yan Pas <yanp.bugz@gmail.com>,
+                   2018-2019 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Tests for the Man reader.
+-}
 module Tests.Readers.Man (tests) where
 
 import Prelude
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
@@ -1,5 +1,16 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Markdown
+   Copyright   : © 2006-2019 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Tests for the Markdown reader.
+-}
 module Tests.Readers.Markdown (tests) where
 
 import Prelude
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
@@ -1,5 +1,16 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Muse
+   Copyright   : © 2017-2019 Alexander Krotov
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Alexander Krotov <ilabdsf@gmail.com>
+   Stability   : alpha
+   Portability : portable
+
+Tests for the Muse reader.
+-}
 module Tests.Readers.Muse (tests) where
 
 import Prelude
@@ -215,6 +226,13 @@
 
       , "Verbatim tag after text" =: "Foo <verbatim>bar</verbatim>" =?> para "Foo bar"
 
+      , "Verbatim tag escapes block level markup" =:
+        T.unlines [ "Foo <verbatim>bar"
+                  , "* Not a heading"
+                  , "</verbatim>baz"
+                  ] =?>
+        para "Foo bar\n* Not a heading\nbaz"
+
       , "Class tag" =: "<class name=\"foo\">bar</class>" =?> para (spanWith ("", ["foo"], []) "bar")
       , "Class tag without name" =: "<class>foobar</class>" =?> para (spanWith ("", [], []) "foobar")
 
@@ -766,6 +784,23 @@
           para (text "Here is a footnote" <>
                 note (para "Footnote contents") <>
                 str ".")
+        , "Simple secondary footnote" =:
+          T.unlines [ "Here is a secondary note{1}."
+                    , ""
+                    , "{1} Secondary note contents"
+                    ] =?>
+          para (text "Here is a secondary note" <>
+                note (para "Secondary note contents") <>
+                str ".")
+        , "Missing footnote" =: "Foo[1]" =?> para "Foo[1]"
+        , "Missing secondary note" =: "Foo{1}" =?> para "Foo{1}"
+        , "Wrong note type" =:
+          T.unlines [ "Here is a secondary note{1}"
+                    , ""
+                    , "Footnote contents[1]"
+                    ] =?>
+          para "Here is a secondary note{1}" <>
+          para "Footnote contents[1]"
         , "Recursive footnote" =:
           T.unlines [ "Start recursion here[1]"
                     , ""
diff --git a/test/Tests/Readers/Odt.hs b/test/Tests/Readers/Odt.hs
--- a/test/Tests/Readers/Odt.hs
+++ b/test/Tests/Readers/Odt.hs
@@ -1,4 +1,16 @@
 {-# LANGUAGE NoImplicitPrelude #-}
+{- |
+   Module      : Tests.Readers.Odt
+   Copyright   : © 2015-2019 John MacFarlane
+                   2015 Martin Linnemann
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Tests for the ODT reader.
+-}
 module Tests.Readers.Odt (tests) where
 
 import Prelude
diff --git a/test/Tests/Readers/Org.hs b/test/Tests/Readers/Org.hs
--- a/test/Tests/Readers/Org.hs
+++ b/test/Tests/Readers/Org.hs
@@ -1,4 +1,15 @@
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Shared
+   Copyright   : © 2014-2019 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert@zeitkraut.de>
+   Stability   : alpha
+   Portability : portable
+
+Tests of the org reader.
+-}
 module Tests.Readers.Org (tests) where
 
 import Test.Tasty (TestTree, testGroup)
diff --git a/test/Tests/Readers/Org/Block.hs b/test/Tests/Readers/Org/Block.hs
--- a/test/Tests/Readers/Org/Block.hs
+++ b/test/Tests/Readers/Org/Block.hs
@@ -1,5 +1,16 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Block
+   Copyright   : © 2014-2019 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert@zeitkraut.de>
+   Stability   : alpha
+   Portability : portable
+
+Tests parsing of org blocks.
+-}
 module Tests.Readers.Org.Block (tests) where
 
 import Prelude
diff --git a/test/Tests/Readers/Org/Block/CodeBlock.hs b/test/Tests/Readers/Org/Block/CodeBlock.hs
--- a/test/Tests/Readers/Org/Block/CodeBlock.hs
+++ b/test/Tests/Readers/Org/Block/CodeBlock.hs
@@ -1,5 +1,16 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Block.CodeBlock
+   Copyright   : © 2014-2019 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert@zeitkraut.de>
+   Stability   : alpha
+   Portability : portable
+
+Test parsing of org code blocks.
+-}
 module Tests.Readers.Org.Block.CodeBlock (tests) where
 
 import Prelude
diff --git a/test/Tests/Readers/Org/Block/Figure.hs b/test/Tests/Readers/Org/Block/Figure.hs
--- a/test/Tests/Readers/Org/Block/Figure.hs
+++ b/test/Tests/Readers/Org/Block/Figure.hs
@@ -1,5 +1,16 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Block.Figure
+   Copyright   : © 2014-2019 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert@zeitkraut.de>
+   Stability   : alpha
+   Portability : portable
+
+Test parsing of org figures.
+-}
 module Tests.Readers.Org.Block.Figure (tests) where
 
 import Prelude
diff --git a/test/Tests/Readers/Org/Block/Header.hs b/test/Tests/Readers/Org/Block/Header.hs
--- a/test/Tests/Readers/Org/Block/Header.hs
+++ b/test/Tests/Readers/Org/Block/Header.hs
@@ -1,5 +1,16 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Block.Header
+   Copyright   : © 2014-2019 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert@zeitkraut.de>
+   Stability   : alpha
+   Portability : portable
+
+Test parsing of org header blocks.
+-}
 module Tests.Readers.Org.Block.Header (tests) where
 
 import Prelude
diff --git a/test/Tests/Readers/Org/Block/List.hs b/test/Tests/Readers/Org/Block/List.hs
--- a/test/Tests/Readers/Org/Block/List.hs
+++ b/test/Tests/Readers/Org/Block/List.hs
@@ -1,5 +1,16 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Block.Header
+   Copyright   : © 2014-2019 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert@zeitkraut.de>
+   Stability   : alpha
+   Portability : portable
+
+Test parsing of org lists.
+-}
 module Tests.Readers.Org.Block.List (tests) where
 
 import Prelude
diff --git a/test/Tests/Readers/Org/Block/Table.hs b/test/Tests/Readers/Org/Block/Table.hs
--- a/test/Tests/Readers/Org/Block/Table.hs
+++ b/test/Tests/Readers/Org/Block/Table.hs
@@ -1,5 +1,16 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Block.Table
+   Copyright   : © 2014-2019 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert@zeitkraut.de>
+   Stability   : alpha
+   Portability : portable
+
+Test parsing of org tables.
+-}
 module Tests.Readers.Org.Block.Table (tests) where
 
 import Prelude
diff --git a/test/Tests/Readers/Org/Directive.hs b/test/Tests/Readers/Org/Directive.hs
--- a/test/Tests/Readers/Org/Directive.hs
+++ b/test/Tests/Readers/Org/Directive.hs
@@ -1,5 +1,16 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Directive
+   Copyright   : © 2014-2019 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert@zeitkraut.de>
+   Stability   : alpha
+   Portability : portable
+
+Tests parsing of org directives (like @#+OPTIONS@).
+-}
 module Tests.Readers.Org.Directive (tests) where
 
 import Prelude
diff --git a/test/Tests/Readers/Org/Inline.hs b/test/Tests/Readers/Org/Inline.hs
--- a/test/Tests/Readers/Org/Inline.hs
+++ b/test/Tests/Readers/Org/Inline.hs
@@ -1,5 +1,16 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Inline
+   Copyright   : © 2014-2019 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert@zeitkraut.de>
+   Stability   : alpha
+   Portability : portable
+
+Tests parsing of org inlines.
+-}
 module Tests.Readers.Org.Inline (tests) where
 
 import Prelude
diff --git a/test/Tests/Readers/Org/Inline/Citation.hs b/test/Tests/Readers/Org/Inline/Citation.hs
--- a/test/Tests/Readers/Org/Inline/Citation.hs
+++ b/test/Tests/Readers/Org/Inline/Citation.hs
@@ -1,5 +1,16 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Inline.Citation
+   Copyright   : © 2014-2019 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert@zeitkraut.de>
+   Stability   : alpha
+   Portability : portable
+
+Test parsing of citations in org input.
+-}
 module Tests.Readers.Org.Inline.Citation (tests) where
 
 import Prelude
diff --git a/test/Tests/Readers/Org/Inline/Note.hs b/test/Tests/Readers/Org/Inline/Note.hs
--- a/test/Tests/Readers/Org/Inline/Note.hs
+++ b/test/Tests/Readers/Org/Inline/Note.hs
@@ -1,5 +1,16 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Inline.Note
+   Copyright   : © 2014-2019 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert@zeitkraut.de>
+   Stability   : alpha
+   Portability : portable
+
+Test parsing of footnotes in org input.
+-}
 module Tests.Readers.Org.Inline.Note (tests) where
 
 import Prelude
diff --git a/test/Tests/Readers/Org/Inline/Smart.hs b/test/Tests/Readers/Org/Inline/Smart.hs
--- a/test/Tests/Readers/Org/Inline/Smart.hs
+++ b/test/Tests/Readers/Org/Inline/Smart.hs
@@ -1,5 +1,16 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Inline.Smart
+   Copyright   : © 2014-2019 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert@zeitkraut.de>
+   Stability   : alpha
+   Portability : portable
+
+Test smart parsing of quotes, apostrophe, etc.
+-}
 module Tests.Readers.Org.Inline.Smart (tests) where
 
 import Prelude
diff --git a/test/Tests/Readers/Org/Meta.hs b/test/Tests/Readers/Org/Meta.hs
--- a/test/Tests/Readers/Org/Meta.hs
+++ b/test/Tests/Readers/Org/Meta.hs
@@ -1,5 +1,16 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Org.Meta
+   Copyright   : © 2014-2019 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert@zeitkraut.de>
+   Stability   : alpha
+   Portability : portable
+
+Tests parsing of org meta data (mostly lines starting with @#+@).
+-}
 module Tests.Readers.Org.Meta (tests) where
 
 import Prelude
diff --git a/test/Tests/Readers/Org/Shared.hs b/test/Tests/Readers/Org/Shared.hs
--- a/test/Tests/Readers/Org/Shared.hs
+++ b/test/Tests/Readers/Org/Shared.hs
@@ -1,4 +1,15 @@
 {-# LANGUAGE NoImplicitPrelude #-}
+{- |
+   Module      : Tests.Readers.Org.Shared
+   Copyright   : © 2014-2019 Albert Krewinkel
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : Albert Krewinkel <albert@zeitkraut.de>
+   Stability   : alpha
+   Portability : portable
+
+Helper functions used by other org tests.
+-}
 module Tests.Readers.Org.Shared
   ( (=:)
   , org
diff --git a/test/Tests/Readers/RST.hs b/test/Tests/Readers/RST.hs
--- a/test/Tests/Readers/RST.hs
+++ b/test/Tests/Readers/RST.hs
@@ -1,6 +1,17 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings   #-}
 {-# LANGUAGE ScopedTypeVariables #-}
+{- |
+   Module      : Tests.Readers.RST
+   Copyright   : © 2006-2019 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Tests for the RST reader.
+-}
 module Tests.Readers.RST (tests) where
 
 import Prelude
diff --git a/test/Tests/Readers/Txt2Tags.hs b/test/Tests/Readers/Txt2Tags.hs
--- a/test/Tests/Readers/Txt2Tags.hs
+++ b/test/Tests/Readers/Txt2Tags.hs
@@ -1,5 +1,17 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Tests.Readers.Txt2Tags
+   Copyright   : © 2014-2019 John MacFarlane,
+                 © 2014 Matthew Pickering
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Tests for the Txt2Tags reader.
+-}
 module Tests.Readers.Txt2Tags (tests) where
 
 import Prelude
diff --git a/test/Tests/Shared.hs b/test/Tests/Shared.hs
--- a/test/Tests/Shared.hs
+++ b/test/Tests/Shared.hs
@@ -1,4 +1,15 @@
 {-# LANGUAGE NoImplicitPrelude #-}
+{- |
+   Module      : Tests.Shared
+   Copyright   : © 2006-2019 John MacFarlane
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley@edu>
+   Stability   : alpha
+   Portability : portable
+
+Tests for functions used in many parts of the library.
+-}
 module Tests.Shared (tests) where
 
 import Prelude
diff --git a/test/Tests/Writers/HTML.hs b/test/Tests/Writers/HTML.hs
--- a/test/Tests/Writers/HTML.hs
+++ b/test/Tests/Writers/HTML.hs
@@ -34,7 +34,7 @@
 tests = [ testGroup "inline code"
           [ "basic" =: code "@&" =?> "<code>@&amp;</code>"
           , "haskell" =: codeWith ("",["haskell"],[]) ">>="
-            =?> "<code class=\"sourceCode haskell\"><span class=\"fu\">&gt;&gt;=</span></code>"
+            =?> "<code class=\"sourceCode haskell\"><span class=\"op\">&gt;&gt;=</span></code>"
           , "nolanguage" =: codeWith ("",["nolanguage"],[]) ">>="
             =?> "<code class=\"nolanguage\">&gt;&gt;=</code>"
           ]
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
@@ -428,6 +428,7 @@
           [ testGroup "string"
             [ "string" =: str "foo" =?> "foo"
             , "escape footnote" =: str "[1]" =?> "<verbatim>[1]</verbatim>"
+            , "escape secondary note" =: 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>"
diff --git a/test/command/1126.md b/test/command/1126.md
--- a/test/command/1126.md
+++ b/test/command/1126.md
@@ -5,9 +5,8 @@
 C&=&D
 \end{eqnarray}
 ^D
-\textbackslash{}begin\{eqnarray\}
-A\&=\&B,\textbackslash{}\textbackslash{} C\&=\&D
-\textbackslash{}end\{eqnarray\}
+\textbackslash begin\{eqnarray\} A\&=\&B,\textbackslash\textbackslash{}
+C\&=\&D \textbackslash end\{eqnarray\}
 ```
 
 ```
diff --git a/test/command/4235.md b/test/command/4235.md
--- a/test/command/4235.md
+++ b/test/command/4235.md
@@ -2,11 +2,11 @@
 % pandoc --id-prefix=foo
 This.^[Has a footnote.]
 ^D
-<p>This.<a href="#foofn1" class="footnote-ref" id="foofnref1"><sup>1</sup></a></p>
-<section class="footnotes">
+<p>This.<a href="#foofn1" class="footnote-ref" id="foofnref1" role="doc-noteref"><sup>1</sup></a></p>
+<section class="footnotes" role="doc-endnotes">
 <hr />
 <ol>
-<li id="foofn1"><p>Has a footnote.<a href="#foofnref1" class="footnote-back">↩</a></p></li>
+<li id="foofn1" role="doc-endnote"><p>Has a footnote.<a href="#foofnref1" class="footnote-back" role="doc-backlink">↩</a></p></li>
 </ol>
 </section>
 ```
diff --git a/test/command/5271.md b/test/command/5271.md
new file mode 100644
--- /dev/null
+++ b/test/command/5271.md
@@ -0,0 +1,12 @@
+```
+% pandoc -f markdown -t native -s
+---
+abstract: |
+  This is the abstract.
+
+  It consists of two paragraphs.
+...
+^D
+Pandoc (Meta {unMeta = fromList [("abstract",MetaBlocks [Para [Str "This",Space,Str "is",Space,Str "the",Space,Str "abstract."],Para [Str "It",Space,Str "consists",Space,Str "of",Space,Str "two",Space,Str "paragraphs."]])]})
+[]
+```
diff --git a/test/command/5285.md b/test/command/5285.md
new file mode 100644
--- /dev/null
+++ b/test/command/5285.md
@@ -0,0 +1,32 @@
+```
+% pandoc -t native
+- a
+
+  b
+- a
+
+- b
+^D
+[BulletList
+ [[Para [Str "a"]
+  ,Para [Str "b"]]
+ ,[Para [Str "a"]]
+ ,[Para [Str "b"]]]]
+```
+
+```
+% pandoc -t native
+- foo
+
+  foo
+- foo
+
+  > foo
+^D
+[BulletList
+ [[Para [Str "foo"]
+  ,Para [Str "foo"]]
+ ,[Para [Str "foo"]
+  ,BlockQuote
+   [Para [Str "foo"]]]]]
+```
diff --git a/test/command/5304.md b/test/command/5304.md
new file mode 100644
--- /dev/null
+++ b/test/command/5304.md
@@ -0,0 +1,24 @@
+````
+% pandoc -f markdown -t markdown
+``` {.markdown}
+`«sträng»`
+
+`` «sträng» ``
+
+``` «sträng» ```
+
+````«sträng»````
+... 
+```
+^D
+``` {.markdown}
+`«sträng»`
+
+`` «sträng» ``
+
+``` «sträng» ```
+
+````«sträng»````
+... 
+```
+````
diff --git a/test/command/5321.md b/test/command/5321.md
new file mode 100644
--- /dev/null
+++ b/test/command/5321.md
@@ -0,0 +1,24 @@
+```
+% pandoc -f jats -t native
+<fig id="fig-1">
+  <caption>
+    <p>bar</p>
+  </caption>
+  <graphic xlink:href="foo.png" xlink:alt-text="baz">
+</fig>
+^D
+[Para [Image ("fig-1",[],[]) [Str "bar"] ("foo.png","fig:")]]
+```
+
+```
+% pandoc -f jats -t native
+<fig id="fig-1">
+  <caption>
+    <title>foo</title>
+    <p>bar</p>
+  </caption>
+  <graphic xlink:href="foo.png" xlink:alt-text="baz">
+</fig>
+^D
+[Para [Image ("fig-1",[],[]) [Str "foo",LineBreak,Str "bar"] ("foo.png","fig:")]]
+```
diff --git a/test/command/ascii.md b/test/command/ascii.md
--- a/test/command/ascii.md
+++ b/test/command/ascii.md
@@ -9,7 +9,7 @@
 pandoc -t latex --ascii
 äéıå
 ^D
-\"{a}\'{e}\i \r{a}
+\"{a}\'{e}\i\r{a}
 ```
 
 ```
diff --git a/test/command/lua-pandoc-state.md b/test/command/lua-pandoc-state.md
--- a/test/command/lua-pandoc-state.md
+++ b/test/command/lua-pandoc-state.md
@@ -1,5 +1,5 @@
 ```
-% pandoc --lua-filter=command/lua-pandoc-state.lua
+% pandoc --lua-filter=command/lua-pandoc-state.lua --data-dir=foo
 Hello
 ^D
    # input files: 0
diff --git a/test/command/tex-group.md b/test/command/tex-group.md
new file mode 100644
--- /dev/null
+++ b/test/command/tex-group.md
@@ -0,0 +1,12 @@
+```
+% pandoc -f latex -t html
+\newenvironment{foo}%
+{\emph\bgroup}%
+{\egroup}
+
+\begin{foo}
+hi
+\end{foo}
+^D
+<p><em>hi</em></p>
+```
diff --git a/test/docx/alternate_document_path.docx b/test/docx/alternate_document_path.docx
new file mode 100644
Binary files /dev/null and b/test/docx/alternate_document_path.docx differ
diff --git a/test/docx/alternate_document_path.native b/test/docx/alternate_document_path.native
new file mode 100644
--- /dev/null
+++ b/test/docx/alternate_document_path.native
@@ -0,0 +1,2 @@
+[Header 1 ("test",[],[]) [Str "Test"]
+,Para [Str "This",Space,Str "is",Space,Emph [Str "italic"],Str ",",Space,Strong [Str "bold"],Str ",",Space,Span ("",["underline"],[]) [Str "underlined"],Str ",",Space,Emph [Span ("",["underline"],[]) [Str "italic",Space,Str "underlined"]],Str ",",Space,Strong [Span ("",["underline"],[]) [Str "bold",Space,Str "underlined"]],Str ",",Space,Emph [Strong [Span ("",["underline"],[]) [Str "bold",Space,Str "italic",Space,Str "underlined"]]],Str "."]]
diff --git a/test/docx/lists_level_override.native b/test/docx/lists_level_override.native
--- a/test/docx/lists_level_override.native
+++ b/test/docx/lists_level_override.native
@@ -27,7 +27,7 @@
  [[BlockQuote
    [Para [Str "Code",Space,Str "documentation"]]]]
 ,BlockQuote
- [Para [Strong [Str "Goal:",Space,Str "Useful,",Space,Str "consistent,",Space,Str "tool",Space,Str "supported",Space,Str "comments",Space]]]
+ [Para [Strong [Str "Goal:",Space,Str "Useful,",Space,Str "consistent,",Space,Str "tool",Space,Str "supported",Space,Str "comments"]]]
 ,Para [Strong [Str "\160"],Str "\160"]
 ,OrderedList (6,Decimal,Period)
  [[BlockQuote
diff --git a/test/docx/sdt_in_footnote.docx b/test/docx/sdt_in_footnote.docx
new file mode 100644
Binary files /dev/null and b/test/docx/sdt_in_footnote.docx differ
diff --git a/test/docx/sdt_in_footnote.native b/test/docx/sdt_in_footnote.native
new file mode 100644
--- /dev/null
+++ b/test/docx/sdt_in_footnote.native
@@ -0,0 +1,1 @@
+[Para [Str "Lorem",Space,Str "ipsum",Space,Str "dolor",Space,Str "sit",Space,Str "amet.",Note [Para [Str "Vgl.",Space,Emph [Str "Bitzios"],Space,Str "u.",Space,Str "a.:",Space,Str "Dissonance",Space,Str "in",Space,Str "the",Space,Str "food",Space,Str "traceability",Space,Str "regulatory",Space,Str "environment",Space,Str "and",Space,Str "food",Space,Str "fraud,",Space,Str "in:",Space,Str "Dries",Space,Str "u.",Space,Str "a.",Space,Str "(Hrsg.):",Space,Str "It\8217s",Space,Str "a",Space,Str "jungle",Space,Str "out",Space,Str "there",Space,Str "-",Space,Str "the",Space,Str "strange",Space,Str "animals",Space,Str "of",Space,Str "economic",Space,Str "organization",Space,Str "in",Space,Str "agri-food",Space,Str "value",Space,Str "chains,",Space,Str "Wageningen",Space,Str "im",Space,Str "Druck,",Space,Str "hier",Space,Str "S.\160\&100-105."]]]]
diff --git a/test/docx/trim_last_inline.docx b/test/docx/trim_last_inline.docx
new file mode 100644
Binary files /dev/null and b/test/docx/trim_last_inline.docx differ
diff --git a/test/docx/trim_last_inline.native b/test/docx/trim_last_inline.native
new file mode 100644
--- /dev/null
+++ b/test/docx/trim_last_inline.native
@@ -0,0 +1,2 @@
+[Para [Strong [Str "Foo",Space,Str "bar."]]
+,Para [Str "Fizz",Space,Str "pop."]]
diff --git a/test/fb2/basic.fb2 b/test/fb2/basic.fb2
--- a/test/fb2/basic.fb2
+++ b/test/fb2/basic.fb2
@@ -12,15 +12,15 @@
 <title>
 <p />
 </title>
-<section>
+<section id="top-level-title">
 <title>
 <p>Top-level title</p>
 </title>
-<section>
+<section id="section">
 <title>
 <p>Section</p>
 </title>
-<section>
+<section id="subsection">
 <title>
 <p>Subsection</p>
 </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 FictionBook titles.</p></section><section><title><p><emphasis>Emphasized</emphasis> <strong>Strong</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 id="simple-title"><title><p>Simple title</p></title><p>This example tests FictionBook titles.</p></section><section id="emphasized-strong-title"><title><p><emphasis>Emphasized</emphasis> <strong>Strong</strong> Title</p></title></section></body></FictionBook>
 
diff --git a/test/ipynb/simple.in.native b/test/ipynb/simple.in.native
new file mode 100644
--- /dev/null
+++ b/test/ipynb/simple.in.native
@@ -0,0 +1,13 @@
+Pandoc (Meta {unMeta = fromList [("jupyter",MetaMap (fromList [("nbformat",MetaInlines [Str "4"]),("nbformat_minor",MetaInlines [Str "5"])]))]})
+[Div ("",["cell","markdown"],[])
+ [Header 1 ("lorem-ipsum",[],[]) [Str "Lorem",Space,Str "ipsum"]
+ ,Para [Strong [Str "Lorem",Space,Str "ipsum"],Space,Str "dolor",Space,Str "sit",Space,Str "amet,",Space,Str "consectetur",Space,Str "adipiscing",Space,Str "elit.",Space,Str "Nunc",Space,Str "luctus",SoftBreak,Str "bibendum",Space,Str "felis",Space,Str "dictum",Space,Str "sodales."]]
+,Div ("",["cell","code"],[])
+ [CodeBlock ("",["python"],[]) "print(\"hello\")"]
+,Div ("",["cell","markdown"],[])
+ [Header 2 ("pyout",[],[]) [Str "Pyout"]]
+,Div ("",["cell","code"],[])
+ [CodeBlock ("",["python"],[]) "from IPython.display import HTML\nHTML(\"\"\"\n<script>\nconsole.log(\"hello\");\n</script>\n<b>HTML</b>\n\"\"\")"]
+,Div ("",["cell","markdown"],[])
+ [Header 2 ("image",[],[]) [Str "Image"]
+ ,Para [Str "This",Space,Str "image",Space,Image ("",[],[]) [Str "the",Space,Str "moon"] ("lalune.jpg",""),Space,Str "will",Space,Str "be",Space,Str "included",Space,Str "as",Space,Str "a",Space,Str "cell",SoftBreak,Str "attachment."]]]
diff --git a/test/ipynb/simple.ipynb b/test/ipynb/simple.ipynb
new file mode 100644
--- /dev/null
+++ b/test/ipynb/simple.ipynb
@@ -0,0 +1,66 @@
+{
+ "cells": [
+  {
+   "cell_type": "markdown",
+   "metadata": {},
+   "source": [
+    "Lorem ipsum\n",
+    "===========\n",
+    "\n",
+    "**Lorem ipsum** dolor sit amet, consectetur adipiscing elit. Nunc luctus\n",
+    "bibendum felis dictum sodales."
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "print(\"hello\")"
+   ]
+  },
+  {
+   "cell_type": "markdown",
+   "metadata": {},
+   "source": [
+    "Pyout\n",
+    "-----"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "from IPython.display import HTML\n",
+    "HTML(\"\"\"\n",
+    "<script>\n",
+    "console.log(\"hello\");\n",
+    "</script>\n",
+    "<b>HTML</b>\n",
+    "\"\"\")"
+   ]
+  },
+  {
+   "cell_type": "markdown",
+   "metadata": {},
+   "source": [
+    "Image\n",
+    "-----\n",
+    "\n",
+    "This image ![the moon](attachment:lalune.jpg) will be included as a cell\n",
+    "attachment."
+   ],
+   "attachments": {
+    "lalune.jpg": {
+     "image/jpeg": "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\nsSjCcDmgVAAbgYoGYJ3nk9qBUAYHAoP/2Q==\n"
+    }
+   }
+  }
+ ],
+ "nbformat": 4,
+ "nbformat_minor": 5,
+ "metadata": {}
+}
diff --git a/test/ipynb/simple.out.native b/test/ipynb/simple.out.native
new file mode 100644
--- /dev/null
+++ b/test/ipynb/simple.out.native
@@ -0,0 +1,13 @@
+Pandoc (Meta {unMeta = fromList [("jupyter",MetaMap (fromList [("nbformat",MetaString "4"),("nbformat_minor",MetaString "5")]))]})
+[Div ("",["cell","markdown"],[])
+ [Header 1 ("lorem-ipsum",[],[]) [Str "Lorem",Space,Str "ipsum"]
+ ,Para [Strong [Str "Lorem",Space,Str "ipsum"],Space,Str "dolor",Space,Str "sit",Space,Str "amet,",Space,Str "consectetur",Space,Str "adipiscing",Space,Str "elit.",Space,Str "Nunc",Space,Str "luctus",SoftBreak,Str "bibendum",Space,Str "felis",Space,Str "dictum",Space,Str "sodales."]]
+,Div ("",["cell","code"],[])
+ [CodeBlock ("",["python"],[]) "print(\"hello\")"]
+,Div ("",["cell","markdown"],[])
+ [Header 2 ("pyout",[],[]) [Str "Pyout"]]
+,Div ("",["cell","code"],[])
+ [CodeBlock ("",["python"],[]) "from IPython.display import HTML\nHTML(\"\"\"\n<script>\nconsole.log(\"hello\");\n</script>\n<b>HTML</b>\n\"\"\")"]
+,Div ("",["cell","markdown"],[])
+ [Header 2 ("image",[],[]) [Str "Image"]
+ ,Para [Str "This",Space,Str "image",Space,Image ("",[],[]) [Str "the",Space,Str "moon"] ("lalune.jpg",""),Space,Str "will",Space,Str "be",Space,Str "included",Space,Str "as",Space,Str "a",Space,Str "cell",SoftBreak,Str "attachment."]]]
diff --git a/test/lhs-test.html b/test/lhs-test.html
--- a/test/lhs-test.html
+++ b/test/lhs-test.html
@@ -83,7 +83,7 @@
 <p><code>unsplit</code> is an arrow that takes a pair of values and combines them to
 return a single value:</p>
 <div class="sourceCode" id="cb1"><pre class="sourceCode haskell literate"><code class="sourceCode haskell"><a class="sourceLine" id="cb1-1" title="1"><span class="ot">unsplit ::</span> (<span class="dt">Arrow</span> a) <span class="ot">=&gt;</span> (b <span class="ot">-&gt;</span> c <span class="ot">-&gt;</span> d) <span class="ot">-&gt;</span> a (b, c) d</a>
-<a class="sourceLine" id="cb1-2" title="2">unsplit <span class="fu">=</span> arr <span class="fu">.</span> <span class="fu">uncurry</span></a>
+<a class="sourceLine" id="cb1-2" title="2">unsplit <span class="ot">=</span> arr <span class="op">.</span> <span class="fu">uncurry</span></a>
 <a class="sourceLine" id="cb1-3" title="3">          <span class="co">-- arr (\op (x,y) -&gt; x `op` y)</span></a></code></pre></div>
 <p><code>(***)</code> 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
diff --git a/test/lhs-test.html+lhs b/test/lhs-test.html+lhs
--- a/test/lhs-test.html+lhs
+++ b/test/lhs-test.html+lhs
@@ -83,7 +83,7 @@
 <p><code>unsplit</code> is an arrow that takes a pair of values and combines them to
 return a single value:</p>
 <div class="sourceCode" id="cb1"><pre class="sourceCode literatehaskell literate"><code class="sourceCode literatehaskell"><a class="sourceLine" id="cb1-1" title="1"><span class="ot">&gt; unsplit ::</span> (<span class="dt">Arrow</span> a) <span class="ot">=&gt;</span> (b <span class="ot">-&gt;</span> c <span class="ot">-&gt;</span> d) <span class="ot">-&gt;</span> a (b, c) d</a>
-<a class="sourceLine" id="cb1-2" title="2"><span class="ot">&gt;</span> unsplit <span class="fu">=</span> arr <span class="fu">.</span> <span class="fu">uncurry</span></a>
+<a class="sourceLine" id="cb1-2" title="2"><span class="ot">&gt;</span> unsplit <span class="ot">=</span> arr <span class="op">.</span> <span class="fu">uncurry</span></a>
 <a class="sourceLine" id="cb1-3" title="3"><span class="ot">&gt;</span>           <span class="co">-- arr (\op (x,y) -&gt; x `op` y)</span></a></code></pre></div>
 <p><code>(***)</code> 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
diff --git a/test/lhs-test.latex b/test/lhs-test.latex
--- a/test/lhs-test.latex
+++ b/test/lhs-test.latex
@@ -109,7 +109,7 @@
 \begin{Shaded}
 \begin{Highlighting}[]
 \OtherTok{unsplit ::}\NormalTok{ (}\DataTypeTok{Arrow}\NormalTok{ a) }\OtherTok{=>}\NormalTok{ (b }\OtherTok{->}\NormalTok{ c }\OtherTok{->}\NormalTok{ d) }\OtherTok{->}\NormalTok{ a (b, c) d}
-\NormalTok{unsplit }\FunctionTok{=}\NormalTok{ arr }\FunctionTok{.} \FunctionTok{uncurry}
+\NormalTok{unsplit }\OtherTok{=}\NormalTok{ arr }\OperatorTok{.} \FunctionTok{uncurry}
           \CommentTok{-- arr (\textbackslash{}op (x,y) -> x `op` y)}
 \end{Highlighting}
 \end{Shaded}
diff --git a/test/pptx/inline_formatting.native b/test/pptx/inline_formatting.native
--- a/test/pptx/inline_formatting.native
+++ b/test/pptx/inline_formatting.native
@@ -1,5 +1,5 @@
-Pandoc (Meta {unMeta = fromList []})
 [Para [Str "Here",Space,Str "are",Space,Str "examples",Space,Str "of",Space,Emph [Str "italics"],Str ",",Space,Strong [Str "bold"],Str ",",Space,Str "and",Space,Strong [Emph [Str "bold",Space,Str "italics"]],Str "."]
 ,Para [Str "Here",Space,Str "is",Space,Strikeout [Str "strook-three"],Space,Str "strike-through",Space,Str "and",Space,SmallCaps [Str "small",Space,Str "caps"],Str "."]
+,Para [Str "Here",Space,Str "is",Space,Span ("",["underline"],[]) [Str "some",Space,Emph [Str "underlined"],Space,Strong [Str "text"]],Str "."]
 ,Para [Str "We",Space,Str "can",Space,Str "also",Space,Str "do",Space,Str "subscripts",Space,Str "(H",Subscript [Str "2"],Str "0)",Space,Str "and",Space,Str "super",Superscript [Str "script"],Str "."]
 ,RawBlock (Format "html") "<!-- Comments don't show up. -->"]
diff --git a/test/pptx/inline_formatting.pptx b/test/pptx/inline_formatting.pptx
Binary files a/test/pptx/inline_formatting.pptx and b/test/pptx/inline_formatting.pptx differ
diff --git a/test/pptx/inline_formatting_templated.pptx b/test/pptx/inline_formatting_templated.pptx
Binary files a/test/pptx/inline_formatting_templated.pptx and b/test/pptx/inline_formatting_templated.pptx differ
diff --git a/test/rst-reader.native b/test/rst-reader.native
--- a/test/rst-reader.native
+++ b/test/rst-reader.native
@@ -96,8 +96,8 @@
 ,OrderedList (1,Decimal,Period)
  [[Para [Str "Item",Space,Str "1,",Space,Str "graf",Space,Str "one."]
   ,Para [Str "Item",Space,Str "1.",Space,Str "graf",Space,Str "two.",Space,Str "The",Space,Str "quick",Space,Str "brown",Space,Str "fox",Space,Str "jumped",Space,Str "over",Space,Str "the",Space,Str "lazy",Space,Str "dog\8217s",SoftBreak,Str "back."]]
- ,[Plain [Str "Item",Space,Str "2."]]
- ,[Plain [Str "Item",Space,Str "3."]]]
+ ,[Para [Str "Item",Space,Str "2."]]
+ ,[Para [Str "Item",Space,Str "3."]]]
 ,Para [Str "Nested:"]
 ,BulletList
  [[Plain [Str "Tab"]
@@ -107,17 +107,17 @@
      [[Plain [Str "Tab"]]]]]]]
 ,Para [Str "Here\8217s",Space,Str "another:"]
 ,OrderedList (1,Decimal,Period)
- [[Plain [Str "First"]]
+ [[Para [Str "First"]]
  ,[Para [Str "Second:"]
   ,BlockQuote
    [BulletList
     [[Plain [Str "Fee"]]
     ,[Plain [Str "Fie"]]
     ,[Plain [Str "Foe"]]]]]
- ,[Plain [Str "Third"]]]
+ ,[Para [Str "Third"]]]
 ,Header 2 ("fancy-list-markers",[],[]) [Str "Fancy",Space,Str "list",Space,Str "markers"]
 ,OrderedList (2,Decimal,TwoParens)
- [[Plain [Str "begins",Space,Str "with",Space,Str "2"]]
+ [[Para [Str "begins",Space,Str "with",Space,Str "2"]]
  ,[Para [Str "and",Space,Str "now",Space,Str "3"]
   ,Para [Str "with",Space,Str "a",Space,Str "continuation"]
   ,OrderedList (4,LowerRoman,Period)
diff --git a/test/rst-reader.rst b/test/rst-reader.rst
--- a/test/rst-reader.rst
+++ b/test/rst-reader.rst
@@ -192,7 +192,7 @@
 
 	Item 1. graf two. The quick brown fox jumped over the lazy dog's
 	back.
-	
+
 2.	Item 2.
 
 3.	Item 3.
diff --git a/test/test-pandoc.hs b/test/test-pandoc.hs
--- a/test/test-pandoc.hs
+++ b/test/test-pandoc.hs
@@ -44,9 +44,10 @@
 import Tests.Helpers (findPandoc)
 import Text.Pandoc.Shared (inDirectory)
 
-tests :: TestTree
-tests = testGroup "pandoc tests" [ Tests.Command.tests
-        , testGroup "Old" Tests.Old.tests
+tests :: FilePath -> TestTree
+tests pandocPath = testGroup "pandoc tests"
+        [ Tests.Command.tests pandocPath
+        , testGroup "Old" (Tests.Old.tests pandocPath)
         , testGroup "Shared" Tests.Shared.tests
         , testGroup "Writers"
           [ testGroup "Native" Tests.Writers.Native.tests
@@ -92,4 +93,4 @@
   inDirectory "test" $ do
     fp <- findPandoc
     putStrLn $ "Using pandoc executable at " ++ fp
-    defaultMain tests
+    defaultMain $ tests fp
diff --git a/test/testsuite.native b/test/testsuite.native
--- a/test/testsuite.native
+++ b/test/testsuite.native
@@ -137,7 +137,7 @@
    ,[Para [Str "this",Space,Str "is",Space,Str "an",Space,Str "example",Space,Str "list",Space,Str "item",SoftBreak,Str "indented",Space,Str "with",Space,Str "spaces"]]]]]
 ,Header 2 ("fancy-list-markers",[],[]) [Str "Fancy",Space,Str "list",Space,Str "markers"]
 ,OrderedList (2,Decimal,TwoParens)
- [[Plain [Str "begins",Space,Str "with",Space,Str "2"]]
+ [[Para [Str "begins",Space,Str "with",Space,Str "2"]]
  ,[Para [Str "and",Space,Str "now",Space,Str "3"]
   ,Para [Str "with",Space,Str "a",Space,Str "continuation"]
   ,OrderedList (4,LowerRoman,Period)
diff --git a/test/writer.asciidoc b/test/writer.asciidoc
--- a/test/writer.asciidoc
+++ b/test/writer.asciidoc
@@ -466,7 +466,11 @@
 * latexmath:[$223$]
 * latexmath:[$p$]-Tree
 * Here’s some display math:
-latexmath:[\[\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}\]]
++
+[latexmath]
+++++
+\[\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}\]
+++++
 * Here’s one that has a line break in it:
 latexmath:[$\alpha + \omega \times x^2$].
 
diff --git a/test/writer.custom b/test/writer.custom
--- a/test/writer.custom
+++ b/test/writer.custom
@@ -263,7 +263,7 @@
 <h2 id="fancy-list-markers">Fancy list markers</h2>
 
 <ol>
-<li>begins with 2</li>
+<li><p>begins with 2</p></li>
 <li><p>and now 3</p>
 
 <p>with a continuation</p>
diff --git a/test/writer.dokuwiki b/test/writer.dokuwiki
--- a/test/writer.dokuwiki
+++ b/test/writer.dokuwiki
@@ -205,7 +205,7 @@
 ===== Fancy list markers =====
 
 <HTML><ol start="2" style="list-style-type: decimal;"></HTML>
-<HTML><li></HTML>begins with 2<HTML></li></HTML>
+<HTML><li></HTML><HTML><p></HTML>begins with 2<HTML></p></HTML><HTML></li></HTML>
 <HTML><li></HTML><HTML><p></HTML>and now 3<HTML></p></HTML>
 <HTML><p></HTML>with a continuation<HTML></p></HTML>
 <HTML><ol start="4" style="list-style-type: lower-roman;"></HTML>
diff --git a/test/writer.fb2 b/test/writer.fb2
--- a/test/writer.fb2
+++ b/test/writer.fb2
@@ -26,25 +26,25 @@
 John Gruber’s markdown test suite.</p>
 <empty-line />
 </section>
-<section>
+<section id="headers">
 <title>
 <p>Headers</p>
 </title>
-<section>
+<section id="level-2-with-an-embedded-link">
 <title>
 <p>Level 2 with an <a l:href="/url">embedded link</a>
 </p>
 </title>
-<section>
+<section id="level-3-with-emphasis">
 <title>
 <p>Level 3 with <emphasis>emphasis</emphasis>
 </p>
 </title>
-<section>
+<section id="level-4">
 <title>
 <p>Level 4</p>
 </title>
-<section>
+<section id="level-5">
 <title>
 <p>Level 5</p>
 </title>
@@ -53,23 +53,23 @@
 </section>
 </section>
 </section>
-<section>
+<section id="level-1">
 <title>
 <p>Level 1</p>
 </title>
-<section>
+<section id="level-2-with-emphasis">
 <title>
 <p>Level 2 with <emphasis>emphasis</emphasis>
 </p>
 </title>
-<section>
+<section id="level-3">
 <title>
 <p>Level 3</p>
 </title>
 <p>with no blank line</p>
 </section>
 </section>
-<section>
+<section id="level-2">
 <title>
 <p>Level 2</p>
 </title>
@@ -77,7 +77,7 @@
 <empty-line />
 </section>
 </section>
-<section>
+<section id="paragraphs">
 <title>
 <p>Paragraphs</p>
 </title>
@@ -93,7 +93,7 @@
 here.</p>
 <empty-line />
 </section>
-<section>
+<section id="block-quotes">
 <title>
 <p>Block Quotes</p>
 </title>
@@ -131,7 +131,7 @@
 <p>And a following paragraph.</p>
 <empty-line />
 </section>
-<section>
+<section id="code-blocks">
 <title>
 <p>Code Blocks</p>
 </title>
@@ -176,11 +176,11 @@
 <empty-line />
 <empty-line />
 </section>
-<section>
+<section id="lists">
 <title>
 <p>Lists</p>
 </title>
-<section>
+<section id="unordered">
 <title>
 <p>Unordered</p>
 </title>
@@ -218,7 +218,7 @@
 <p>• Minus 3</p>
 <empty-line />
 </section>
-<section>
+<section id="ordered">
 <title>
 <p>Ordered</p>
 </title>
@@ -255,7 +255,7 @@
 <p>3. Item 3.</p>
 <empty-line />
 </section>
-<section>
+<section id="nested">
 <title>
 <p>Nested</p>
 </title>
@@ -280,7 +280,7 @@
 <p>3. Third</p>
 <empty-line />
 </section>
-<section>
+<section id="tabs-and-spaces">
 <title>
 <p>Tabs and spaces</p>
 </title>
@@ -297,11 +297,12 @@
 indented with spaces</p>
 <empty-line />
 </section>
-<section>
+<section id="fancy-list-markers">
 <title>
 <p>Fancy list markers</p>
 </title>
 <p>(2) begins with 2</p>
+<empty-line />
 <p>(3) and now 3</p>
 <empty-line />
 <p>    with a continuation</p>
@@ -326,7 +327,7 @@
 <empty-line />
 </section>
 </section>
-<section>
+<section id="definition-lists">
 <title>
 <p>Definition Lists</p>
 </title>
@@ -440,7 +441,7 @@
 <p>1. sublist</p>
 <p>2. sublist</p>
 </section>
-<section>
+<section id="html-blocks">
 <title>
 <p>HTML Blocks</p>
 </title>
@@ -484,7 +485,7 @@
 <p>Hr’s:</p>
 <empty-line />
 </section>
-<section>
+<section id="inline-markup">
 <title>
 <p>Inline Markup</p>
 </title>
@@ -521,7 +522,7 @@
 because of the unescaped spaces: a^b c^d, a~b c~d.</p>
 <empty-line />
 </section>
-<section>
+<section id="smart-quotes-ellipses-dashes">
 <title>
 <p>Smart quotes, ellipses, dashes</p>
 </title>
@@ -537,7 +538,7 @@
 <p>Ellipses…and…and….</p>
 <empty-line />
 </section>
-<section>
+<section id="latex">
 <title>
 <p>LaTeX</p>
 </title>
@@ -564,7 +565,7 @@
 <p>Here’s a LaTeX table:</p>
 <empty-line />
 </section>
-<section>
+<section id="special-characters">
 <title>
 <p>Special Characters</p>
 </title>
@@ -597,11 +598,11 @@
 <p>Minus: -</p>
 <empty-line />
 </section>
-<section>
+<section id="links">
 <title>
 <p>Links</p>
 </title>
-<section>
+<section id="explicit">
 <title>
 <p>Explicit</p>
 </title>
@@ -627,7 +628,7 @@
 <p>
 <a l:href="">Empty</a>.</p>
 </section>
-<section>
+<section id="reference">
 <title>
 <p>Reference</p>
 </title>
@@ -647,7 +648,7 @@
 <p>Foo <a l:href="/url/">bar</a>.</p>
 <p>Foo <a l:href="/url/">biz</a>.</p>
 </section>
-<section>
+<section id="with-ampersands">
 <title>
 <p>With ampersands</p>
 </title>
@@ -656,7 +657,7 @@
 <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>
+<section id="autolinks">
 <title>
 <p>Autolinks</p>
 </title>
@@ -682,7 +683,7 @@
 <empty-line />
 </section>
 </section>
-<section>
+<section id="images">
 <title>
 <p>Images</p>
 </title>
@@ -691,7 +692,7 @@
 <p>Here is a movie <image l:href="#image2" l:type="inlineImageType" alt="movie" /> icon.</p>
 <empty-line />
 </section>
-<section>
+<section id="footnotes">
 <title>
 <p>Footnotes</p>
 </title>
diff --git a/test/writer.haddock b/test/writer.haddock
--- a/test/writer.haddock
+++ b/test/writer.haddock
@@ -236,6 +236,7 @@
 #fancy-list-markers#
 
 (2) begins with 2
+
 (3) and now 3
 
     with a continuation
diff --git a/test/writer.html4 b/test/writer.html4
--- a/test/writer.html4
+++ b/test/writer.html4
@@ -196,7 +196,7 @@
 </ul>
 <h2 id="fancy-list-markers">Fancy list markers</h2>
 <ol start="2" style="list-style-type: decimal">
-<li>begins with 2</li>
+<li><p>begins with 2</p></li>
 <li><p>and now 3</p>
 <p>with a continuation</p>
 <ol start="4" style="list-style-type: lower-roman">
diff --git a/test/writer.html5 b/test/writer.html5
--- a/test/writer.html5
+++ b/test/writer.html5
@@ -199,7 +199,7 @@
 </ul>
 <h2 id="fancy-list-markers">Fancy list markers</h2>
 <ol start="2" type="1">
-<li>begins with 2</li>
+<li><p>begins with 2</p></li>
 <li><p>and now 3</p>
 <p>with a continuation</p>
 <ol start="4" type="i">
@@ -526,25 +526,25 @@
 <p>Here is a movie <img src="movie.jpg" alt="movie" /> icon.</p>
 <hr />
 <h1 id="footnotes">Footnotes</h1>
-<p>Here is a footnote reference,<a href="#fn1" class="footnote-ref" id="fnref1"><sup>1</sup></a> and another.<a href="#fn2" class="footnote-ref" id="fnref2"><sup>2</sup></a> This should <em>not</em> be a footnote reference, because it contains a space.[^my note] Here is an inline note.<a href="#fn3" class="footnote-ref" id="fnref3"><sup>3</sup></a></p>
+<p>Here is a footnote reference,<a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a> and another.<a href="#fn2" class="footnote-ref" id="fnref2" role="doc-noteref"><sup>2</sup></a> This should <em>not</em> be a footnote reference, because it contains a space.[^my note] Here is an inline note.<a href="#fn3" class="footnote-ref" id="fnref3" role="doc-noteref"><sup>3</sup></a></p>
 <blockquote>
-<p>Notes can go in quotes.<a href="#fn4" class="footnote-ref" id="fnref4"><sup>4</sup></a></p>
+<p>Notes can go in quotes.<a href="#fn4" class="footnote-ref" id="fnref4" role="doc-noteref"><sup>4</sup></a></p>
 </blockquote>
 <ol type="1">
-<li>And in list items.<a href="#fn5" class="footnote-ref" id="fnref5"><sup>5</sup></a></li>
+<li>And in list items.<a href="#fn5" class="footnote-ref" id="fnref5" role="doc-noteref"><sup>5</sup></a></li>
 </ol>
 <p>This paragraph should not be part of the note, as it is not indented.</p>
-<section class="footnotes">
+<section class="footnotes" role="doc-endnotes">
 <hr />
 <ol>
-<li id="fn1"><p>Here is the footnote. It can go anywhere after the footnote reference. It need not be placed at the end of the document.<a href="#fnref1" class="footnote-back">↩</a></p></li>
-<li id="fn2"><p>Here’s the long note. This one contains multiple blocks.</p>
+<li id="fn1" role="doc-endnote"><p>Here is the footnote. It can go anywhere after the footnote reference. It need not be placed at the end of the document.<a href="#fnref1" class="footnote-back" role="doc-backlink">↩</a></p></li>
+<li id="fn2" role="doc-endnote"><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>
 <pre><code>  { &lt;code&gt; }</code></pre>
-<p>If you want, you can indent every line, but you can also be lazy and just indent the first line of each block.<a href="#fnref2" class="footnote-back">↩</a></p></li>
-<li id="fn3"><p>This is <em>easier</em> to type. Inline notes may contain <a href="http://google.com">links</a> and <code>]</code> verbatim characters, as well as [bracketed text].<a href="#fnref3" class="footnote-back">↩</a></p></li>
-<li id="fn4"><p>In quote.<a href="#fnref4" class="footnote-back">↩</a></p></li>
-<li id="fn5"><p>In list.<a href="#fnref5" class="footnote-back">↩</a></p></li>
+<p>If you want, you can indent every line, but you can also be lazy and just indent the first line of each block.<a href="#fnref2" class="footnote-back" role="doc-backlink">↩</a></p></li>
+<li id="fn3" role="doc-endnote"><p>This is <em>easier</em> to type. Inline notes may contain <a href="http://google.com">links</a> and <code>]</code> verbatim characters, as well as [bracketed text].<a href="#fnref3" class="footnote-back" role="doc-backlink">↩</a></p></li>
+<li id="fn4" role="doc-endnote"><p>In quote.<a href="#fnref4" class="footnote-back" role="doc-backlink">↩</a></p></li>
+<li id="fn5" role="doc-endnote"><p>In list.<a href="#fnref5" class="footnote-back" role="doc-backlink">↩</a></p></li>
 </ol>
 </section>
 </body>
diff --git a/test/writer.icml b/test/writer.icml
--- a/test/writer.icml
+++ b/test/writer.icml
@@ -400,7 +400,7 @@
           <BasedOn type="object">$ID/NormalParagraphStyle</BasedOn>
         </Properties>
       </ParagraphStyle>
-      <ParagraphStyle Self="ParagraphStyle/NumList &gt; first &gt; beginsWith-2" Name="NumList &gt; first &gt; beginsWith-2" NumberingExpression="^#.^t" NumberingLevel="1" BulletsAndNumberingListType="NumberedList" LeftIndent="0">
+      <ParagraphStyle Self="ParagraphStyle/NumList &gt; first &gt; beginsWith-2 &gt; Paragraph" Name="NumList &gt; first &gt; beginsWith-2 &gt; Paragraph" NumberingExpression="^#.^t" NumberingLevel="1" BulletsAndNumberingListType="NumberedList" LeftIndent="0">
         <Properties>
           <BasedOn type="object">$ID/NormalParagraphStyle</BasedOn>
         </Properties>
@@ -1105,7 +1105,7 @@
   </CharacterStyleRange>
 </ParagraphStyleRange>
 <Br />
-<ParagraphStyleRange NumberingStartAt="2" AppliedParagraphStyle="ParagraphStyle/NumList &gt; first &gt; beginsWith-2" NumberingContinue="false">
+<ParagraphStyleRange NumberingStartAt="2" AppliedParagraphStyle="ParagraphStyle/NumList &gt; first &gt; beginsWith-2 &gt; Paragraph" NumberingContinue="false">
   <CharacterStyleRange AppliedCharacterStyle="$ID/NormalCharacterStyle">
     <Content>begins with 2</Content>
   </CharacterStyleRange>
diff --git a/test/writer.jats b/test/writer.jats
--- a/test/writer.jats
+++ b/test/writer.jats
@@ -835,7 +835,7 @@
   <title>Images</title>
   <p>From “Voyage dans la Lune” by Georges Melies (1902):</p>
   <fig>
-    <caption>lalune</caption>
+    <caption><p>lalune</p></caption>
     <graphic mimetype="image" mime-subtype="jpeg" xlink:href="lalune.jpg" xlink:title="Voyage dans la Lune" />
   </fig>
   <p>Here is a movie
diff --git a/test/writer.latex b/test/writer.latex
--- a/test/writer.latex
+++ b/test/writer.latex
@@ -719,7 +719,7 @@
 H\textsubscript{many~of~them}O.
 
 These should not be superscripts or subscripts, because of the unescaped
-spaces: a\^{}b c\^{}d, a\textasciitilde{}b c\textasciitilde{}d.
+spaces: a\^{}b c\^{}d, a\textasciitilde b c\textasciitilde d.
 
 \begin{center}\rule{0.5\linewidth}{\linethickness}\end{center}
 
@@ -741,7 +741,7 @@
 
 Dashes between numbers: 5--7, 255--66, 1987--1999.
 
-Ellipses\ldots{}and\ldots{}and\ldots{}.
+Ellipses\ldots and\ldots and\ldots.
 
 \begin{center}\rule{0.5\linewidth}{\linethickness}\end{center}
 
diff --git a/test/writer.markdown b/test/writer.markdown
--- a/test/writer.markdown
+++ b/test/writer.markdown
@@ -239,6 +239,7 @@
 ------------------
 
 (2) begins with 2
+
 (3) and now 3
 
     with a continuation
diff --git a/test/writer.mediawiki b/test/writer.mediawiki
--- a/test/writer.mediawiki
+++ b/test/writer.mediawiki
@@ -198,7 +198,7 @@
 == Fancy list markers ==
 
 <ol start="2" style="list-style-type: decimal;">
-<li>begins with 2</li>
+<li><p>begins with 2</p></li>
 <li><p>and now 3</p>
 <p>with a continuation</p>
 <ol start="4" style="list-style-type: lower-roman;">
diff --git a/test/writer.native b/test/writer.native
--- a/test/writer.native
+++ b/test/writer.native
@@ -137,7 +137,7 @@
    ,[Para [Str "this",Space,Str "is",Space,Str "an",Space,Str "example",Space,Str "list",Space,Str "item",SoftBreak,Str "indented",Space,Str "with",Space,Str "spaces"]]]]]
 ,Header 2 ("fancy-list-markers",[],[]) [Str "Fancy",Space,Str "list",Space,Str "markers"]
 ,OrderedList (2,Decimal,TwoParens)
- [[Plain [Str "begins",Space,Str "with",Space,Str "2"]]
+ [[Para [Str "begins",Space,Str "with",Space,Str "2"]]
  ,[Para [Str "and",Space,Str "now",Space,Str "3"]
   ,Para [Str "with",Space,Str "a",Space,Str "continuation"]
   ,OrderedList (4,LowerRoman,Period)
diff --git a/test/writer.opendocument b/test/writer.opendocument
--- a/test/writer.opendocument
+++ b/test/writer.opendocument
@@ -1115,7 +1115,6 @@
     <style:style style:name="P38" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L21">
     </style:style>
     <style:style style:name="P39" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L22">
-      <style:paragraph-properties fo:margin-top="0in" fo:margin-bottom="0in" />
     </style:style>
     <style:style style:name="P40" style:family="paragraph" style:parent-style-name="Text_20_body" style:list-style-name="L23">
       <style:paragraph-properties fo:margin-top="0in" fo:margin-bottom="0in" />
diff --git a/test/writer.opml b/test/writer.opml
--- a/test/writer.opml
+++ b/test/writer.opml
@@ -39,7 +39,7 @@
   </outline>
   <outline text="Tabs and spaces" _note="-   this is a list item indented with tabs&#10;&#10;-   this is a list item indented with spaces&#10;&#10;    -   this is an example list item indented with tabs&#10;&#10;    -   this is an example list item indented with spaces">
   </outline>
-  <outline text="Fancy list markers" _note="1.  begins with 2&#10;2.  and now 3&#10;&#10;    with a continuation&#10;&#10;    1.  sublist with roman numerals, starting with 4&#10;    2.  more items&#10;        1.  a subsublist&#10;        2.  a subsublist&#10;&#10;Nesting:&#10;&#10;1.  Upper Alpha&#10;    1.  Upper Roman.&#10;        1.  Decimal start with 6&#10;            1.  Lower alpha with paren&#10;&#10;Autonumbering:&#10;&#10;1.  Autonumber.&#10;2.  More.&#10;    1.  Nested.&#10;&#10;Should not be a list item:&#10;&#10;M.A. 2007&#10;&#10;B. Williams&#10;&#10;------------------------------------------------------------------------">
+  <outline text="Fancy list markers" _note="1.  begins with 2&#10;&#10;2.  and now 3&#10;&#10;    with a continuation&#10;&#10;    1.  sublist with roman numerals, starting with 4&#10;    2.  more items&#10;        1.  a subsublist&#10;        2.  a subsublist&#10;&#10;Nesting:&#10;&#10;1.  Upper Alpha&#10;    1.  Upper Roman.&#10;        1.  Decimal start with 6&#10;            1.  Lower alpha with paren&#10;&#10;Autonumbering:&#10;&#10;1.  Autonumber.&#10;2.  More.&#10;    1.  Nested.&#10;&#10;Should not be a list item:&#10;&#10;M.A. 2007&#10;&#10;B. Williams&#10;&#10;------------------------------------------------------------------------">
   </outline>
 </outline>
 <outline text="Definition Lists" _note="Tight using spaces:&#10;&#10;apple  &#10;red fruit&#10;&#10;orange  &#10;orange fruit&#10;&#10;banana  &#10;yellow fruit&#10;&#10;Tight using tabs:&#10;&#10;apple  &#10;red fruit&#10;&#10;orange  &#10;orange fruit&#10;&#10;banana  &#10;yellow fruit&#10;&#10;Loose:&#10;&#10;apple  &#10;red fruit&#10;&#10;orange  &#10;orange fruit&#10;&#10;banana  &#10;yellow fruit&#10;&#10;Multiple blocks with italics:&#10;&#10;*apple*  &#10;red fruit&#10;&#10;contains seeds, crisp, pleasant to taste&#10;&#10;*orange*  &#10;orange fruit&#10;&#10;    { orange code block }&#10;&#10;&gt; orange block quote&#10;&#10;Multiple definitions, tight:&#10;&#10;apple  &#10;red fruit&#10;&#10;computer&#10;&#10;orange  &#10;orange fruit&#10;&#10;bank&#10;&#10;Multiple definitions, loose:&#10;&#10;apple  &#10;red fruit&#10;&#10;computer&#10;&#10;orange  &#10;orange fruit&#10;&#10;bank&#10;&#10;Blank line after term, indented marker, alternate markers:&#10;&#10;apple  &#10;red fruit&#10;&#10;computer&#10;&#10;orange  &#10;orange fruit&#10;&#10;1.  sublist&#10;2.  sublist">
diff --git a/test/writer.org b/test/writer.org
--- a/test/writer.org
+++ b/test/writer.org
@@ -294,6 +294,7 @@
    :END:
 
 2) begins with 2
+
 3) and now 3
 
    with a continuation
diff --git a/test/writer.plain b/test/writer.plain
--- a/test/writer.plain
+++ b/test/writer.plain
@@ -244,6 +244,7 @@
 Fancy list markers
 
 (2) begins with 2
+
 (3) and now 3
 
     with a continuation
diff --git a/test/writer.rst b/test/writer.rst
--- a/test/writer.rst
+++ b/test/writer.rst
@@ -261,6 +261,7 @@
 ------------------
 
 (2) begins with 2
+
 (3) and now 3
 
     with a continuation
diff --git a/test/writer.rtf b/test/writer.rtf
--- a/test/writer.rtf
+++ b/test/writer.rtf
@@ -132,7 +132,7 @@
 {\pard \ql \f0 \sa180 \li720 \fi-360 \endash \tx360\tab this is an example list item indented with tabs\par}
 {\pard \ql \f0 \sa180 \li720 \fi-360 \endash \tx360\tab this is an example list item indented with spaces\sa180\sa180\par}
 {\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Fancy list markers\par}
-{\pard \ql \f0 \sa0 \li360 \fi-360 (2)\tx360\tab begins with 2\par}
+{\pard \ql \f0 \sa180 \li360 \fi-360 (2)\tx360\tab begins with 2\par}
 {\pard \ql \f0 \sa180 \li360 \fi-360 (3)\tx360\tab and now 3\par}
 {\pard \ql \f0 \sa180 \li360 \fi0 with a continuation\par}
 {\pard \ql \f0 \sa0 \li720 \fi-360 iv.\tx360\tab sublist with roman numerals, starting with 4\par}
diff --git a/test/writer.texinfo b/test/writer.texinfo
--- a/test/writer.texinfo
+++ b/test/writer.texinfo
@@ -453,6 +453,7 @@
 @enumerate 2
 @item
 begins with 2
+
 @item
 and now 3
 
diff --git a/test/writer.textile b/test/writer.textile
--- a/test/writer.textile
+++ b/test/writer.textile
@@ -212,7 +212,7 @@
 h2(#fancy-list-markers). Fancy list markers
 
 <ol start="2" style="list-style-type: decimal;">
-<li>begins with 2</li>
+<li><p>begins with 2</p></li>
 <li><p>and now 3</p>
 <p>with a continuation</p>
 <ol start="4" style="list-style-type: lower-roman;">
diff --git a/trypandoc/index.html b/trypandoc/index.html
--- a/trypandoc/index.html
+++ b/trypandoc/index.html
@@ -89,8 +89,12 @@
         <option value="commonmark">CommonMark</option>
         <option value="creole">Creole</option>
         <option value="docbook">DocBook</option>
+        <option value="dokuwiki">DokuWiki</option>
+        <option value="fb2">FB2</option>
         <option value="haddock">Haddock markup</option>
         <option value="html">HTML</option>
+        <option value="jats">JATS</option>
+        <option value="ipynb">Jupyter Notebook (ipynb)</option>
         <option value="latex">LaTeX</option>
         <option value="man">Man</option>
         <option value="markdown" selected>Markdown (pandoc)</option>
@@ -119,7 +123,8 @@
       </label>
       <select id="to">
         <option value="S5">S5</option>
-        <option value="asciidoc">AsciiDoc</option>
+        <option value="asciidoc">AsciiDoc (original)</option>
+        <option value="asciidoctor">AsciiDoc (asciidoctor-flavored)</option>
         <option value="beamer">LaTeX Beamer</option>
         <option value="commonmark">CommonMark</option>
         <option value="context">ConTeXt</option>
@@ -127,12 +132,13 @@
         <option value="docbook5">DocBook v5</option>
         <option value="dokuwiki">DokuWiki</option>
         <option value="dzslides">DZSlides</option>
-        <option value="dzslides">dzslides</option>
         <option value="haddock">Haddock markup</option>
         <option value="html4">HTML 4</option>
         <option value="html5" selected>HTML 5</option>
         <option value="icml">ICML</option>
+        <option value="jats">JATS</option>
         <option value="json">JSON</option>
+        <option value="ipynb">Jupyter Notebook (ipynb)</option>
         <option value="latex">LaTeX</option>
         <option value="man">Man</option>
         <option value="ms">Ms</option>
@@ -153,6 +159,7 @@
         <option value="rtf">RTF</option>
         <option value="slideous">Slideous</option>
         <option value="slidy">Slidy</option>
+        <option value="tei">TEI</option>
         <option value="texinfo">Texinfo</option>
         <option value="textile">Textile</option>
         <option value="zimwiki">ZimWiki</option>
diff --git a/trypandoc/trypandoc.hs b/trypandoc/trypandoc.hs
--- a/trypandoc/trypandoc.hs
+++ b/trypandoc/trypandoc.hs
@@ -1,5 +1,16 @@
 {-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{- |
+   Module      : Main
+   Copyright   : © 2014-2019 John MacFarlane <jgm@berkeley.edu>
+   License     : GNU GPL, version 2 or above
+
+   Maintainer  : John MacFarlane <jgm@berkeley.edu>
+   Stability   : alpha
+   Portability : portable
+
+Provides a webservice which allows to try pandoc in the browser.
+-}
 module Main where
 import Prelude
 import Network.Wai.Handler.CGI
